如何在执行完成之前等到从 Firebase 存储下载完成 swift
How to wait till download from Firebase Storage is completed before executing a completion swift
在以下从 Firebase 存储下载图像的模型中,它完成了 for 循环,但完成块中的打印语句显示“[]”。然而,片刻之后下载到达并显示在数组中。如何在执行完成之前等待图像完全下载并进入数组并稍后重新加载 table?
查看模型:下载图像
//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)
}
由于加载图像数据是一个异步操作,任何需要在图像加载后 运行 的代码都需要在完成处理程序中,从那里调用,或者以其他方式同步。
一个简单的方法是统计加载完成的图片数量,然后调用once it matches the length of the
数组:
imageArray.removeAll()
for imageRef in products! {
let storageRef = self.storage.reference(withPath: imageRef.image!)
storageRef.getData(maxSize: 1 * 1024 * 1024) { [self] data, error in
if let error = error {
print (error)
} else {
//Image Returned Successfully:
let image = UIImage(data: data!)
//Add Images to the Array:
imageArray.append(image!)
//
if (imageArray.count == products!.count) {
completion (true)
}
}
}
}
在以下从 Firebase 存储下载图像的模型中,它完成了 for 循环,但完成块中的打印语句显示“[]”。然而,片刻之后下载到达并显示在数组中。如何在执行完成之前等待图像完全下载并进入数组并稍后重新加载 table?
查看模型:下载图像
//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)
}
由于加载图像数据是一个异步操作,任何需要在图像加载后 运行 的代码都需要在完成处理程序中,从那里调用,或者以其他方式同步。
一个简单的方法是统计加载完成的图片数量,然后调用once it matches the length of the
数组:
imageArray.removeAll()
for imageRef in products! {
let storageRef = self.storage.reference(withPath: imageRef.image!)
storageRef.getData(maxSize: 1 * 1024 * 1024) { [self] data, error in
if let error = error {
print (error)
} else {
//Image Returned Successfully:
let image = UIImage(data: data!)
//Add Images to the Array:
imageArray.append(image!)
//
if (imageArray.count == products!.count) {
completion (true)
}
}
}
}