I’m having trouble loading images asyncronously between my view controllers. I have a tableView controller that opens up a collection view controller when you click on a row. When the collection view opens, it hangs for a while as the images are downloaded from the internet.
I put the following code in collectionView:cellForItemAtIndexPath:, but this results in synchronous loading, and makes the program lag.
-(UICollectionViewCell *) collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"CollectionCell";
CollectionCell *cell = [cv dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
NSData *imageData = [NSData dataWithContentsOfURL:[self.theImage objectAtIndex:indexPath.row]];
cell.itemImage.image = [UIImage imageWithData:imageData];
return cell;
}
My question is, where and how do I implement code such that the collection view loads the empty cells while the images are downloading (and then appear after they download)?
I tried to use grand central dispatch but I couldn’t quite figure out. If someone could help point me in the right direction, I’d appreciate it.
For that kind of lazy loading, I always use:
https://github.com/rs/SDWebImage
This solves most of my problems when I want to async load images in tables/collectionviews etc.
It supports caching of images already downloaded and just saves a lot of headaches.