我正在尝试从Firebase存储中获取一些图像,并将其附加到空的FBPicArray变量中。
let storage = Storage.storage()
let imageNames = ["firstImage.jpg", "seccondImage.jpg", "thirdImage.jpg"]
var FBPicArray = [UIImage]()
func loadFirebaseIMG(resultPicArray: @escaping([UIImage]) -> ()) {
for item in imageNames {
let storageref = storage.reference(withPath: "Images/\(item)")
storageref.getData(maxSize: 1 * 1024 * 1024) { (data, error) in
if let error = error {
print("FB storage error:", error)
} else {
let image = UIImage(data: data!)
self.FBPicArray.append(image!)
resultPicArray(self.FBPicArray)
}
}
}
}
太好了。调用该函数时,我可以访问FBPicArray,但是当我要执行诸如在数组中有图像时显示单元格数量之类的事情时,就会遇到问题:
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
loadFirebaseIMG { (img) in
}
return FBPicArray.count
}
在运行函数时,当我像上面的示例那样操作时,没有显示任何单元格,但是,当我尝试将return语句放入loadFirebaseIMG函数中时,此方法也不起作用。如何在功能之外访问这些数据以在代码的其他地方使用?
答案 0 :(得分:0)
您不需要任何补全,而是更改为
func loadFirebaseIMG() {
for item in imageNames {
let storageref = storage.reference(withPath: "Images/\(item)")
storageref.getData(maxSize: 1 * 1024 * 1024) { (data, error) in
if let error = error {
print("FB storage error:", error)
} else {
let image = UIImage(data: data!)
self.fBPicArray.append(image!)
self.collectionView.reloadData() // reload the collection when you receive an image , performance tip is to use insertItems
}
}
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return fBPicArray.count
}
并在loadFirebaseIMG
内调用viewDidLoad
,如果您需要全部加载它们,则最后刷新我不建议的集合,然后选择DispatchGroup