SDWebImage – awesome library for caching images

SDWebImage Caching Images

SDWebImage is a library that provides a category for UIImageView with support for remote images coming from the web. This library handles all tasks asynchronously, and the performances are amazing.

I have tried many images caching libraries but I got “stuck” with this one for more than a year. Not only that it’s performing good, but also the implementation is short and clean which is also an important factor for me when picking a suitable library to use.

In this tutorial, I will show you 2 things that you need the most: caching images with UIImageView and prefetching images.

 

  1. UIImageView caching example: 

[imageView sd_setImageWithURL:[NSURL URLWithString:@"http://theappspace.com/wp-content/uploads/2016/05/swift.png"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    2. Prefetching images

#import "ImageFetcher.h"
#import <UIImageView+WebCache.h>
#import <SDWebImagePrefetcher.h>

@implementation ImageFetcher


+ (void)prefetchImages:(NSArray *)images
    {
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        SDWebImagePrefetcher *prefetcher = [SDWebImagePrefetcher sharedImagePrefetcher];
        NSMutableArray *urlsToDownload = [NSMutableArray array];
        for (NSString *img in images) {
            NSURL *imageUrlToDownload = [NSURL URLWithString:img];
            
            if ([manager cachedImageExistsForURL:imageUrlToDownload]) {
                continue;
            }
            
            if (imageUrlToDownload != nil){
                [urlsToDownload addObject:imageUrlToDownload];
            }
        }
        if (urlsToDownload.count != 0) {
            [prefetcher prefetchURLs:urlsToDownload];
        }
    }

    
}

@end

 

Simple, isn’t it?

 

Leave a Reply

Your email address will not be published. Required fields are marked *