【发布时间】:2021-12-07 18:04:12
【问题描述】:
我正在使用 firebase 来保存和加载我的图像。我在 Xcode 中创建了一个新视图,并且正在使用与加载配置文件图像相同的代码。然而,这现在抛出一个错误,说 url 字符串是 nil。图片 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
}
})
}
【问题讨论】:
-
在你学会正确使用它之前不要使用!...永远不要使用它。除此之外,在某些情况下,例如从网络加载图像,url 只是临时的,并在不久后被删除。您需要在线程同步之前加载数据(或将图像复制到某处),因为届时它将丢失(删除)。我不知道你的字典是什么以及你从哪里得到它,但也许这会给你一个线索来解决你的问题。
-
哦,如果url是http url?是的,不要那样做。使用
URLSession下载您的图像。或者使用像 Nuke 这样的库来为你处理这个问题。 -
@Jacob 我已经添加了我正在从 firebase 调用的完整代码
标签: swift xcode dispatch-queue