I have a function that runs a loop the trigers another function for each item in the loop but it seems to not run the function as many times as there is items in the array.
Here are my functions.
func startLoop(completion: @escaping (_ finished: Bool) -> ()) {
print("Tony items amount is \(tempImgUrls.count)")
for item in tempImgUrls {
dispatchGroup.enter()
print("Tony begin loop")
let img = item["imgUrl"]
let name = item["name"]
downloadImages(img: img!, name: name!, completion: { (complete) in
print("Tony mid loop")
self.dispatchGroup.leave()
})
}
dispatchGroup.notify(queue: DispatchQueue.main) {
print("Tony end loop")
completion(true)
}
}
func downloadImages(img: String, name: String, completion: @escaping (_ finished: Bool) -> ()) {
imageShown.sd_setImage(with: URL(string: img), completed: { (image, error, cacheType, imageUrl) in
let personImg = image!
let personId = name
let post = Person(personImage: personImg, personId: personId)
self.finalImgUrls.append(post)
completion(true)
print("Tony array is with images person is \(self.finalImgUrls)")
print("Tony items 2 amount is \(self.finalImgUrls.count)")
})
}
}
And this is the print out in consol, as you can see it prints the loop start first then the mid 1 time and the end 1 time with one item appended at the end instead of 4 like what is fed in.
Tony items amount is 4
Tony begin loop
Tony begin loop
Tony begin loop
Tony begin loop
Tony mid loop
Tony array is with images person is [AppName.Person]
Tony items 2 amount is 1