Audrey Hipburn
Audrey Hipburn

Reputation: 83

SDWebImageCache precaching images

I'm using the SDWebImage plugin and I have run into the following scenario: I have two UIViewController's A and B. In UIViewControllerB I am loading a series of 10 - 15 images from the web in a UIImageView with the following code:

UIImageView *imageView = [[UIImageView alloc] init];
[imageView sd_setImageWithURL:[NSURL URLWithString:[sourceDictionary objectForKey:@"image"]]
                  placeholderImage:[UIImage imageNamed:@"placeholder"]];

This works well. Except that I begin downloading these images once the user loads UIViewControllerB. I was wondering if there was a way from me to begin to pre-cache or begin downloading these images while the user is still on UIViewControllerA so that when the user gets to UIViewControllerB they see a shorter delay? How would I do this in a manner so that the image isnt downloaded twice if the user switches to the second viewcontroller while a download is taking place?

Upvotes: 1

Views: 158

Answers (1)

teamnorge
teamnorge

Reputation: 794

Possible workaround could be to implement custom download manager using Singleton pattern, so it's available from both A and B.

Then you can track the list of image URLs requested to be downloaded as well as completed handlers to be called when download completed.

First you check that the download of the image with same URL is not taking place already and then either add image into the list and completed handler or just add new handler. You can use dictionary as a storage, using URL as a key.

Then you can use SDWebImageManager with downloadImageWithURL method, where on completed method you remove image from the list and trigger corresponding completed handlers.

So at B you know that the download has been finished. You do not necessary need to cache images manually with SDWebImageCache, let SDWebImage to do it for you automatically, so when your on completed method get called just do the same as you do, but since image has been already downloaded SDWebImage will take it from the cache. Alternatively you can send back UIImage downloaded into the completed handler.

Upvotes: 1

Related Questions