这是我用来从 Firebase 存储中检索图像文件的代码:
let group = DispatchGroup()
print("starting ImageSetting")
group.enter()
for query in friendArray {
if imageList[query.uid] == nil {
print("going through iteration")
self.profpicRef.child("profile_pic/" + query.uid + ".jpeg").getData(maxSize: 1
* 1024 * 1024) { (data, error) in
print("accessing image")
if let error = error {
self.imageList[query.uid] = self.defaultImage
} else {
self.imageList[query.uid] = UIImage(data: data!)
}
}
}
}
group.leave()
我在ViewWillAppear
. 我也尝试过,ViewDIdAppear
但结果没有改变。
这是我在第一次运行时调用这个方法得到的结果
starting ImageSetting
going through iteration
going through iteration
going through iteration
going through iteration
going through iteration
going through iteration
going through iteration
going through iteration
going through iteration
going through iteration
going through iteration
going through iteration
所以第一次运行getData()
没有通过。然而,在第二次运行时,该功能正常工作,我得到了所有的图像
有没有办法解决这个问题?
我怀疑问题在于您没有真正正确使用调度组。这里的问题是for
循环本质上是立即执行和完成的——是的,这些回调将在稍后调用,但这不是代码告诉调度组离开的地方。
(此外,我notify
在您的示例代码中没有看到调用,但我假设这是稍后调用的代码的一部分。)
因此,如果您在代码中执行某些依赖于已加载这些图像的操作,则会出现错误。而且我怀疑它可能会第二次工作,因为您正在抓取缓存数据,这可能确实为您的目的执行得足够快。
修复它的一种方法是确保在正确的位置添加调度组元素。也许像这样......
let group = DispatchGroup()
print("starting ImageSetting")
for query in friendArray {
if imageList[query.uid] == nil {
print("going through iteration")
group.enter()
self.profpicRef.child("profile_pic/" + query.uid + ".jpeg").getData(maxSize: 1
* 1024 * 1024) { (data, error) in
print("accessing image")
if let error = error {
self.imageList[query.uid] = self.defaultImage
} else {
self.imageList[query.uid] = UIImage(data: data!)
}
group.leave()
}
}
}
group.notify(queue: .main) {
print("Images done loading")
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句