I noticed that apps like Intagram uses UICollectionViews
to display the feed of photos.
I also noticed that the cells for these photos is somehow placed on screen
use
[self.collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
instead of
[self.collectionView reloadData];
here indexPath
is the NSIndexPath
Object for the corresponding UICollectionViewCell
Object
The technique you want to implement is called lazy loading. Since you are using AFNetworking
it will be easier to implement this in your case. Each of your collection view cell needs to have a UIImageView
to display the image. Use the UIImageView+AFNetworking.h
category and set the correct image URL by calling method
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
// ....
[cell.imageView setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
// ...
return cell;
}
Placeholder is the image which will be displayed until required image is downloaded. This will simply do the required job for you.
Note: By default, URL requests have a cache policy of NSURLCacheStorageAllowed
and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use setImageWithURLRequest:placeholderImage:success:failure:
.
Also, for you reference, if you want to implement lazy loading of images yourself, follow this Apple sample code. This is for UITableView
but same technique can be used for UICollectionView
as well.
Hope that helps!
Use following to load image Async in cell in cellForItemAtIndexPath delegate method
let url = URL(string: productModel.productImage)
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async(execute: {
collectionViewCell.imageView.image = UIImage(data: data!)
});
Implement protocol "UICollectionViewDataSourcePrefetching" in you ViewController as
class ViewController: UIViewController , UICollectionViewDataSourcePrefetching {
Set following delegates to your collection view in storyboard (see the attached image) or programmatically
In ViewController's viewDidLoad method
collectionView.delegate = self
collectionView.dataSource = self
collectionView.prefetchDataSource = self