2

I have array with image urls and I need to download all images, add all of them to array before passing to view.

I am using that snippet for downloading single image

var images: [UIImage] = []
ImageDownloader.default.downloadImage(with: URL(string: "http://abcd.com/image1.jpg")!, options: [], progressBlock: nil) {
        (image, error, url, data) in
        images.append(image!)
      }

but this is only downloading 1 image. How can I download multiple images at same time and run callback after all of them finished ?

mTuran
  • 1,846
  • 4
  • 32
  • 58

1 Answers1

7

For each URL you can call downloadImage this will start downloading all images at the same time, when each image is fetched you can add it to the images array, you know that all images finished downloading when the size of the images array is the same as the size of the URLs array and then you can call your callback

imageURLS.forEach({ 
    ImageDownloader.default.downloadImage(with: $0, options: [], progressBlock: nil) {
       (image, error, url, data) in
        images.append(image!)
        if images.count == imageURLS.count {
            callback()
        }
    }
})
juanjo
  • 3,737
  • 3
  • 39
  • 44
  • I need to run callback after all tasks finished, thanks. – mTuran Dec 04 '16 at 17:10
  • You're right Gert; the callback is called when the images array is the same size as the URLs array mTuran, which means that all images finished downloading, if there is no error of course, in this case is a closure named `callback` but it can be a function. – juanjo Dec 04 '16 at 17:39
  • I'm using Kingfisher, and looking for a way to know, when a loop something like this finishes. What if there's an error!? – Frade May 07 '20 at 23:53
  • You have the error available in the closure, the same way you append the image to an array you could append the error to an array or have a reference to the last error. – juanjo May 08 '20 at 13:46