我有一个function
检索我正在使用的一些数据for-loop
。里面可能asynchronous function
会调用an但不一定。在我正在做的事情完成后,我completion
也在开火。问题是我需要循环按顺序执行!loop
DispatchGroup
这是我的代码:
// dispatch group to make sure completion only fires when for loop is finished
let group = DispatchGroup()
// append every Wish to array at wishIDX
for document in querySnapshot!.documents {
group.enter()
let documentData = document.data()
let imageUrlString = document["imageUrl"] as? String ?? ""
let wishIDX = documentData["wishlistIDX"] as? Int ?? 0
let imageView = UIImageView()
imageView.image = UIImage()
if let imageUrl = URL(string: imageUrlString) {
let resource = ImageResource(downloadURL: imageUrl)
imageView.kf.setImage(with: resource) { (result) in
switch result {
case .success(_):
print("success")
dataSourceArrayWithWishes[wishIDX].wishes.append(Wish(image: imageView.image!)
group.leave()
case .failure(_):
dataSourceArrayWithWishes[wishIDX].wishes.append(Wish(image: UIImage())
print("fail")
group.leave()
}
}
} else {
dataSourceArrayWithWishes[wishIDX].wishes.append(Wish(image: imageView.image!)
group.leave()
}
}
// for loop is finished -> fire completion
group.notify(queue: DispatchQueue.main) {
completion(true, dataSourceArrayWithWishes)
}
我看到了这个非常相似的问题,但我正在努力将其应用于我的案例,因为在我的案例中,asynchronous call
如果没有image
. 有谁可以帮我离开这里吗?