【发布时间】:2019-05-03 20:14:39
【问题描述】:
我正在从 Firebase 获取用户图片。一个用户最多可以在数据库中上传 6 张图像。我想以正确的顺序(0-6)将图像下载到 CollectionView 中。
当我尝试使用 CompletionHandler 时,它无法按我的意愿工作。 CollectionView 的重新加载在获取图像之前很久就完成了,没有显示图像,因为图像是在调用 reloadData 之后放入数组中的。
不胜感激有关此问题的帮助。
这是我的代码:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
downloadAndReload()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayImages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "swipeCell", for: indexPath as IndexPath) as! ProfileCardCollectionViewCell
let image = self.arrayImages[indexPath.item]
cell.swipeProfileImage.image = image
print("lägger ut cell")
return cell
}
func downloadAndReload(){
cachedImage(completion: { message in
print(message)
self.swipeCollectionView.reloadData()
})
}
func cachedImage(completion: @escaping (_ message: String) -> Void){
if let uid = Auth.auth().currentUser?.uid{
for i in 0...6{
let url = URL(string: uid+String(i))
SDWebImageManager.shared.loadImage(with: url, options: .refreshCached, progress: .none ,completed: { (image, data, error, _, _, _) in
if let error = error{
print("Couldn't download image")
self.downloadImage(i: i, completion: {_ in
})
}
else{
print("Could download image")
self.arrayImages.append(image!)
}
})
}
completion("DONE")
}
}
func downloadImage(i: Int, completion: @escaping (_ fetchWorked: String) -> Void){
print("Downloading Image")
let g = DispatchGroup()
g.enter()
if let uid = Auth.auth().currentUser?.uid{
let imagesStorageRef = Storage.storage().reference().child("profilepic/").child(uid+String(i))
imagesStorageRef.downloadURL { url, error in
guard let url = url else { return }
SDWebImageManager.shared.loadImage(with: url, options: .refreshCached, progress: .none ,completed: { (image, data, error, _, _, _) in
if let error = error{
}
else{
self.arrayImages.append(image!)
}
})
g.leave()
}
g.notify(queue: .main, execute: {
completion("Done")
})
}
}
【问题讨论】:
标签: swift firebase for-loop closures completionhandler