0

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)
    }
et moi
  • 127
  • 1
  • 1
  • 9
  • After looking at this again I feel like I may have been leading you down a bad path so I retracted my answer. I'm not real comfortable with what is going on here in general. I would suggest rethinking what you're trying to achieve here. What is the end goal? What user experience are you solving for? – Chris Wagner Dec 16 '15 at 06:37
  • Hey George, just to clarify, is your problem that `completionHandler(cardImages.count)` returns before you've downloaded all the photos? – Laurent Rivard Dec 16 '15 at 19:36
  • @ChrisWagner the end goal is to add the images to a custom `viewcontroller`, snapshot the `viewcontroller` and save the image to be used later – et moi Dec 16 '15 at 22:14
  • @LaurentRivard yeah that's currently the issue – et moi Dec 16 '15 at 22:15
  • Checkout the answer from `gnasher729` on this post: http://stackoverflow.com/questions/25528695/dispatch-semaphore-wait-does-not-wait-on-semaphore. – Laurent Rivard Dec 17 '15 at 15:55

0 Answers0