gpt4 book ai didi

ios - 如何在 swiftui 的 if-condition 语句中显示警报 View ?

转载 作者:行者123 更新时间:2023-12-01 16:05:08 26 4
gpt4 key购买 nike

我遇到了一个问题,我正在尝试实现一个警报 View 以显示图像何时错误或其他什么以及何时按下提交按钮以显示警报 View 。正如您在我下面的代码中看到的那样,我正试图在我的 if 条件中实现一个警报 View ?是否有可能感谢您的帮助。

这是我的代码:

 @State private var showsAlert = false
func uploadImage(image:UIImage){

if let imageData = image.jpegData(compressionQuality: 1){

let storage = Storage.storage()

f let imageName = "image1"
let folderName = "folder1"
let path = "\(folderName)/\(imageName)"


storage.reference(withPath: path).putData(imageData, metadata: nil){
(_, err) in
if let err = err {
print("an error has occurred - \(err.localizedDescription)")

// .alert(isPresented: $showsAlert) {
// Alert(title: Text("Photo Upload Error"), message: Text("an error has occurred - \(err.localizedDescription)"), dismissButton: .default(Text("OK")))
// }

} else {


print("Your photos have been successfully uploaded. Keep a lookout for your photos in our social media posts!")
// .alert(isPresented: $showsAlert) {
//
// Alert(title: Text("Success!"), message: Text("Your photos have been successfully uploaded. Keep a lookout for your photos in our social media posts!"), dismissButton: .default(Text("OK")))
//
// }
}

}

} else {
print("coldn't unwrap/case image to data")
}


}

最佳答案

您只需在函数中设置@State 变量并在 View 的body 中显示警报:

struct ContentView: View {
@State private var showsAlert = false
@State private var errorDescription: String?

var alertTitle: String {
errorDescription != nil ? "Photo Upload Error" : "Photo Uploaded correctly"
}

var alertMessage: String {
if let error = errorDescription {
return error
}
return "Photo uploaded"
}

var body: some View {
Text("view")
.alert(isPresented: $showsAlert) {
Alert(
title: Text(alertTitle),
message: Text(alertMessage),
dismissButton: .default(Text("OK"))
)
}
}

func uploadImage(image: UIImage) {
if let imageData = image.jpegData(compressionQuality: 1) {
...

storage.reference(withPath: path).putData(imageData, metadata: nil) {
_, err in
if let err = err {
print("an error has occurred - \(err.localizedDescription)")
// set @State variables
DispatchQueue.main.async {
self.errorDescription = err.localizedDescription
}
}
DispatchQueue.main.async {
self.showsAlert = true
}
}
}
}
}

关于ios - 如何在 swiftui 的 if-condition 语句中显示警报 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63784354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com