Search code examples
iosswiftsdwebimage

SDWebImage Prefetching with completion block


My aim is to cover a collectionView with a 'loading screen' which will not be hidden until all the images from a pre-fetched array of images have been loaded into cache by SDWebImage.

In my viewDidLoad I have retrieved an array of image URL's which will be used to populate a collection view. Once they are retrieved I plan on using SDWebImagePrefetcher to process the array.

so far I have the below:

let urls : [URL] = [URL(string: "https://trialwebsite.com/image1.png")!,URL(string: "https://trialwebsite.com/image2.png")!,URL(string: "https://trialwebsite.com/image3.png")!]

 SDWebImagePrefetcher.shared().prefetchURLs(urls)

What I am struggling to figure out is how to use a completion block to hide the 'loading' screen once all the images have been processed.

Any help much appreciated.


Solution

  • You could use prefetchURLs:completed: instead of using prefetchURLs, it would has a completion block (closure since you are writing Swift) parameter that contains finishedCount and skippedCount unsigned integers:

    as mentioned in the method documentation:

    completionBlock

    block to be called when prefetching is completed

    which is seems to be what are you asking for. So it would be something like:

    SDWebImagePrefetcher.shared().prefetchURLs(urls) { finishedCount, skippedCount in
        // hide the 'loading' screen...
        // you might need to implement your own counting logic 
        // to make sure that all images have been processed.
    }