There are already a lot of posts and blogs which talk about image showing optimization in UICollectionView, but most of them are paging disabled and the most common way is to cancel requesting images in the middle part while scrolling fast, and load visible cells when stop scrolling.
In this post, I will discuss about how to make image display smoothly while enable UICollectionView paging.
Version 0: basic native method
[cell.imageView setImage: [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]]];
Version 1: AFNetworking 2.0 (import “UIImageView+AFNetworking.h”)
[cell.imageView setImageWithURL:[NSURL URLWithString:postCoverURL]];
Version 2: preload image in an extra UIImageView array (imageViews) as cache for next cell + method in Version 1
[self loadImageView:(unsigned int) (indexPath.row + 1)];
- (void)loadImageView:(unsigned)page { if (!self.imageViews) { self.imageViews = [[NSMutableArray alloc] initWithCapacity:[self.imgURLs count]]; } if (page >= [self.imgURLs count]) { return; } NSURL *url = self.imgURLs[page]; if ([self.imageViews count] > page) { UIImageView *imageView = ((UIImageView *) self.imageViews[page]); [imageView setImageWithURL:url]; } else { UIImageView *imageView = [[UIImageView alloc] init]; [imageView setImageWithURL:url]; [self.imageViews addObject:imageView]; } }
Version 3: cancel loading images skipped while scrolling fast
Version 4: fetch small group of cell content (images, posts) each batch and load next batch when touch the end, like Houzz iOS app does.
Version 5: download other cell related information (thumbnail, text, etc.) initially rather than load with primary content
Version 6: fetch the appropriate size image to display on screen, do not download large one and resize
Version 7: use low level 3rd part library if use AFNetworking or other network request library
Version 8: use appropriate placeholder image in transition
Version 9: compress images used in UICollectionViewCell when upload if its size is over threshold, balance between quality and loading speed, compress as much as possible since the image size is the network request source.
Version 10: compress images based on their density (byte/pixel), which will control image quality in more details
Resource:
Advanced Swift: Updated for Swift 3
iPhone Advanced Projects (Books for Professionals by Professionals)
iOS Core Animation: Advanced Techniques
Swift Cookbook – 50 Recipes to Help You Harness Swift
development of advanced and practical iOS 6(Chinese Edition)
Reference:
Image caching with AFNetworking
How Does Caching Work in AFNetworking? AFImageCache & NSURLCache Explained
iOS-image-caching-sdwebimage-vs-fastimage
Disk caching with AFNetworking
Avoiding-image-decompression-sickness
How is SDWebImage better than X
How to cache server response in iOS app