我遇到了一个问题,我试图实现一个警报视图,以显示何时图像有问题或什么东西以及何时按下提交按钮以显示警报视图。正如您在下面的代码中看到的那样,我正在尝试在if条件内实现警报视图?能否感谢您的帮助。
这是我的代码:
@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")
}
}
答案 0 :(得分:2)
您只需要在函数中设置@State
变量,并在视图的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
}
}
}
}
}