-2

I'm using a code I got off here to download some images and present them in a collection view. Heres the code:

func downloadImage (url: URL, completion: () -> Void){
    let session = URLSession(configuration: .default)
    let downloadPicTask = session.dataTask(with: url) { (data, response, error) in
        if let e = error {
            print("Error downloading image \(e)")
        } else {
            if let res = response as? HTTPURLResponse {
            print("Downloaded image with response code \(res.statusCode)")
                if let imageData = data {
                let image = UIImage(data: imageData)
                self.globalImages.append(image!)
                print("what does this say?-->", self.globalImages.count) 
                } else {
                print("Couldn't get image: Image is nil")
            }
        } else {
            print("Couldn't get response code for some reason")
            }
        }
    }
    completion()
    downloadPicTask.resume()
}

And I'm calling the download image in view did load where URL is the URL. (this URL works and I can download image).

downloadImage(url: url) { () -> () in
           collectionView.ReloadData()
            }

The completion handler I've tried calls reloadData() way too soon. I'm wanting it to be called when the image is finished downloading? so then the image can be displayed as soon as it's downloaded. What is wrong with this code?

Please help!

Dan.code
  • 431
  • 2
  • 14

1 Answers1

0

You would call the completion handler as soon as you have the image. So, in your code:

       if let imageData = data {
            let image = UIImage(data: imageData)
            self.globalImages.append(image!)
            print("what does this say?-->", self.globalImages.count)
            // call the completion handler here

Be aware, though, that you are likely to have other issues caused by data sharing across multiple threads, and also that your idea of storing the downloaded images successively in an array (globalImages) is not likely to work correctly.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • it doesn't let me put the completion handler there. It has error `Escaping closure captures non-escaping parameter 'completion'` – Dan.code Jan 31 '20 at 04:21
  • https://stackoverflow.com/questions/59784963/swift-escaping-closure-captures-non-escaping-parameter-oncompletion – matt Jan 31 '20 at 04:45