如何等到从 Firebase 存储下载完成后再执行完成快速
在下面从 Firebase Storage 下载图像的模型中,它完成了 for 循环,但完成块中的 print 语句显示“[]”。然而,片刻之后,下载就到达了。显示在数组中。我如何等待图像完全下载&在执行完成之前进入数组稍后重新加载表格?
查看型号:下载图片
//Firebase Cloud Storage Reference:
let storage = Storage.storage()
public var imageArray: [UIImage] = []
public func fetchProductImages(completion: @escaping (Result<UIImage, Error>) -> Void) {
//Clear Image Array:
imageArray.removeAll()
for imageRef in products! {
//Access to Image inside a Collection:
let storageRef = self.storage.reference(withPath: imageRef.image!)
//Download in Memory with a Maximum Size of 1MB (1 * 1024 * 1024 Bytes):
storageRef.getData(maxSize: 1 * 1024 * 1024) { [self] data, error in
if let error = error {
//Error:
print (error)
} else {
//Image Returned Successfully:
let image = UIImage(data: data!)
//Add Images to the Array:
imageArray.append(image!)
}
}
}
print (imageArray)
completion (true)
}
In the below model that downloads the images from Firebase Storage it completes the for loop, but the print statement in the completion block shows "[]". However, moments later the downloads arrive & show in the array. How do I wait for the images to fully download & enter into the array before executing the completion & reload a table later?
View Model: Downloads Image
//Firebase Cloud Storage Reference:
let storage = Storage.storage()
public var imageArray: [UIImage] = []
public func fetchProductImages(completion: @escaping (Result<UIImage, Error>) -> Void) {
//Clear Image Array:
imageArray.removeAll()
for imageRef in products! {
//Access to Image inside a Collection:
let storageRef = self.storage.reference(withPath: imageRef.image!)
//Download in Memory with a Maximum Size of 1MB (1 * 1024 * 1024 Bytes):
storageRef.getData(maxSize: 1 * 1024 * 1024) { [self] data, error in
if let error = error {
//Error:
print (error)
} else {
//Image Returned Successfully:
let image = UIImage(data: data!)
//Add Images to the Array:
imageArray.append(image!)
}
}
}
print (imageArray)
completion (true)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于加载图像数据是一个异步操作,因此在图像加载后需要运行的任何代码都需要位于完成处理程序内,从那里调用,或者以其他方式同步。
一个简单的方法是计算已完全加载的图像数量,并在与数组长度匹配时调用
:
Since loading the image data is an asynchronous operation, any code that needs to run after the images have loaded will need to be inside the completion handler, be called from there, or be otherwise synchronized.
A simple way is to count the number of images that have completely loaded, and call
once it matches the length of the
array: