I currently have a function with a completionHandler which should return the count of download images from an array but unfortunately the function returns too early and the count is always 0 (It seems the completionHandler value is being returned before the function is complete. How can I fix this?)
func loadFunctions(){
//Append results to data array
getData{sta in
if (sta == 0){
self.downloadImages{ handler in
print(handler)
}
}
}
}
func downloadImages (completionHandler: (Int) -> ()) -> () {
for index in data {
let URLRequest = NSURLRequest(URL: NSURL(string: index.artworkUrl512)!)
downloader.downloadImage(URLRequest: URLRequest) { response in
if let image = response.result.value {
cardImages.append(image)
print(image)
}
}
}
completionHandler(cardImages.count)
}
Function using semaphore
func downloadImages (completionHandler: (Int) -> ()) -> () {
let semaphore = dispatch_semaphore_create(0)
for index in data {
dispatch_semaphore_signal(semaphore)
let URLRequest = NSURLRequest(URL: NSURL(string: index.artworkUrl512)!)
downloader.downloadImage(URLRequest: URLRequest) { response in
if let image = response.result.value {
cardImages.append(image)
print(image)
}
}
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
completionHandler(cardImages.count)
}