I have a function
to retrieve some data which I am doing with a for-loop
. Inside that it is possible that an asynchronous function
is called but not necessarily. I am also firing a completion
after the loop
is finished which I am doing with DispatchGroup
. The problem is that I need the loop to execute in order!
This is my code:
// 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)
}
I saw this question which is quite similar but I am struggling to apply this to my case because in my case there is the possibility that I dont make asynchronous call
if there is no image
. Can anyone help me out here?
You need to use
DispatchSemaphore
to execute them in order