Mitesh Dobareeya Mitesh Dobareeya - 1 year ago 122
iOS Question

How to load images faster in UICollectionView?

I have array of images which contain fullpath of image.
I stored images in document directory.
The problem is when i scroll down the image load time in collection view is slow so scrolling is also very poor.
Referencing this code to make it faster.

But the problem is images not displayed in cell.
My collection view code is

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
AlbumImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AlbumImageCell" forIndexPath:indexPath];
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"AlbumImageCell" owner:self options:nil] objectAtIndex:0];
NSString *path=[documentImage objectAtIndex:indexPath.row];

NSURL *url = [NSURL URLWithString:path];
// note that this can be a web url or file url

ImageRequest *request = [[ImageRequest alloc] initWithURL:url];

UIImage *image = [request cachedResult];

if (image) {
UIImageView *imageView = (UIImageView *)[cell viewWithTag:127];
imageView.image = image;
} else {
[request startWithCompletion:^(UIImage *image, NSError *error) {
if (image && [[collectionView indexPathsForVisibleItems] containsObject:indexPath]) {
[self.album_ImageView reloadItemsAtIndexPaths:@[indexPath]];
return cell;

I got null in UIImage.
Please help me to solve this.

Answer Source

I highly recommend this library for loading images in collection view cell or table view using NSURL.


As far as i know, it's one of the commonly used asynchronous image downloader and probably uses some internal caching mechanism. You need to use import different category headers based on the UI element where you want to show the image. In this case, you need to include

#import <SDWebImage/UIImageView+WebCache.h>

Please find the SAMPLE code as i have shown below which i have used for setting the image view for each and very cell within a collection view cell.

NSURL *imageURL = [NSURL URLWithString:@""];

[_sampleImageView sd_setImageWithURL:imageURL placeholderImage:[UIImage defaultPlaceHolderImage] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

        if (image == nil) {
            UIImage *localImage = [UIImage someLocalImage];
            if (localImage == nil) {
                localImage = [UIImage defaultPlaceHolderImage];

            _sampleImageView.image = localImage;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download