我正在使用 firebase 來保存和加載我的影像。我在 Xcode 中創建了一個新視圖,并使用與加載組態檔影像相同的代碼。然而,這現在拋出一個錯誤,說 url 字串為零。影像 url 資料在“DispatchQueue.global().async”后消失。什么可能導致這種情況,我該如何跟蹤?很奇怪這段代碼如何適用于其他視圖,但對于這個新視圖卻拋出錯誤。
let businessProfilePicture = dictionary["profPicString"] as! String
if businessProfilePicture.count > 0 {
let url = URL(string: businessProfilePicture)
print(url)
print("printing the url here to check")
DispatchQueue.global().async {
let dataURL = try? Data(contentsOf: url!)
print(dataURL)
print("printing the data url here")
DispatchQueue.main.async {
print(dataURL)
print("Printing Data to check")
let image = UIImage(data: dataURL!)?.potter_circleo
self.businessProfilePicture.contentMode = UIView.ContentMode.scaleAspectFill
self.businessProfilePicture.image = image
}
}


完整代碼
func getWorkLocation() {
let uid = Auth.auth().currentUser?.uid
var profPicURL: String = ""
Database.database().reference().child("employees").child(uid!).child("Business").observe(.value, with: { snapshot in
if snapshot.exists() {
let dictionary = snapshot.value as? NSDictionary
self.businessName.text = dictionary?["businessName"] as? String
self.businessStreet.text = dictionary?["businessStreet"] as? String
self.businessCity.text = dictionary?["businessCity"] as? String
profPicURL = dictionary?["profPicString"] as! String
// set image
if profPicURL.count > 0 {
let url = URL(string: profPicURL)
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
let image = UIImage(data: data!)?.potter_circle
self.businessProfilePicture.contentMode = UIView.ContentMode.scaleAspectFill
self.businessProfilePicture.image = image
}
}
} else {
let image = UIImage(named: "profile picture")?.potter_circle
self.businessProfilePicture.contentMode = UIView.ContentMode.scaleAspectFill
self.businessProfilePicture.image = image
}
} else {
self.businessName.text = ""
self.businessStreet.text = "Go to Add Work Location to send request"
self.businessCity.text = ""
self.deleteButton.isEnabled = false
}
})
}
uj5u.com熱心網友回復:
您確定您創建的 URLprofPicURL是正確創建的嗎?
URL(string:)可以失敗并回傳nil。如果你繼續隱式地解包它,Data(contentsOf: url!)你會崩潰。
同樣,try? Data(contentsOf: url)可以回傳 nil。如果是這樣,那么當你隱式地解開它時,UIImage(data: data!)你會崩潰。
正如 Jacob 在評論中所說,您需要了解更多關于隱式解包的選項。為了讓你開始,你可以像這樣構建你的代碼:
if let url = URL(string: profPicURL) {
DispatchQueue.global().async {
if let data = try? Data(contentsOf: url),
let image = UIImage(data: data)?.potter_circle
{
DispatchQueue.main.async {
self.businessProfilePicture.contentMode = UIView.ContentMode.scaleAspectFill
self.businessProfilePicture.image = image
}
} else {
// raise an an error or set self.businessProfilePicture.image to a generic image or something
}
}
} else {
// raise an an error or set self.businessProfilePicture.image to a generic image or something
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/329702.html
