ios - 按顺序执行带有可选异步调用的 for 循环
问题描述
我有一个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
. 有谁可以帮我离开这里吗?
解决方案
您需要DispatchSemaphore
按顺序执行它们
//MARK: getWishes
static func getWishes(dataSourceArray: [Wishlist], completion: @escaping (_ success: Bool, _ dataArray: [Wishlist]) -> Void){
var dataSourceArrayWithWishes = dataSourceArray
let db = Firestore.firestore()
let userID = Auth.auth().currentUser!.uid
let group = DispatchGroup()
let dispatchSemaphore = DispatchSemaphore(value: 0)
for list in dataSourceArray {
group.enter()
db.collection("users").document(userID).collection("wishlists").document(list.name).collection("wünsche").order(by: "wishCounter").getDocuments() { ( querySnapshot, error) in
defer {
print("leaving scope:\(String(describing: querySnapshot?.count))")
group.leave()
}
if let error = error {
print(error.localizedDescription)
completion(false, dataSourceArrayWithWishes)
} else {
// dispatch group to make sure completion only fires when for loop is finished
// append every Wish to array at wishIDX
let dispatchQueue = DispatchQueue(label: "taskQueue")
dispatchQueue.async {
for document in querySnapshot!.documents {
group.enter()
let documentData = document.data()
let name = documentData["name"] as? String ?? ""
let link = documentData["link"] as? String ?? ""
let price = documentData["price"] as? String ?? ""
let note = documentData["note"] as? String ?? ""
let imageUrlString = document["imageUrl"] as? String ?? ""
let wishIDX = documentData["wishlistIDX"] as? Int ?? 0
if let imageUrl = URL(string: imageUrlString) {
KingfisherManager.shared.retrieveImage(with: imageUrl, options: nil, progressBlock: nil, completionHandler: { result in
var image = UIImage()
switch result {
case .success(let abc):
image = abc.image
case .failure(let error):
print(error)
break
}
dataSourceArrayWithWishes[wishIDX].wishes.append(Wish(name: name, link: link, price: price, note: note, image: image, checkedStatus: false))
print("Signal for next one")
dispatchSemaphore.signal()
group.leave()
})
print("wait for next one")
dispatchSemaphore.wait()
} else {
dataSourceArrayWithWishes[wishIDX].wishes.append(Wish(name: name, link: link, price: price, note: note, image: nil, checkedStatus: false))
}
}
}
// for loop is finished -> fire completion
}
}
}
group.notify(queue: DispatchQueue.main) {
print("notify")
completion(true, dataSourceArrayWithWishes)
}
}
推荐阅读
- java - 循环内的 Jsoup .data()
- apache-spark - 如何解决 Pyspark 中的分析异常错误
- php - HTML/PHP 表单不工作,提交按钮什么也不做?
- javascript - 努力将 venmo 集成到我的 webap
- angular - 如何使用 Angular 6 材料使自定义步进组件可重复使用
- python-3.x - QMenu 仅在调用 QPushButton.menu() 时显示在 QPushButton
- php - 提交表单后变量未存储
- internet-explorer - Mat-icons 在 Internet Explorer 中不起作用
- javascript - MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型
- javascript - Python 请求模块在本地提供“请启用 JavaScript 以查看页面内容”但在 AMI 和 Heroku 服务器上工作