I have a ViewController with a CollectionView inside. When the view loads, the visible cells (9 cells) are shown correctly. When I scroll down, I want to load the visible items
If you are targeting iOS 8.0 and above you should use collectionView:willDisplayCell:forItemAtIndexPath:
to kick off your download. If using iOS 7.0 you should continue to use collectionView:cellForItemAtIndexPath:
.
In your imageLoaderDidFinishDownloading:
callback you should check to see if the index path in question is still visible. If it is, retrieve the corresponding cell and update its image view. If the cell isn't visible, then your work is done. Calling -reloadData
for every image completion is doing a lot of expensive work and could have significant UX issues if your user is currently mid-scroll of the table and you reset its contents. You are also potentially doing the UIImageJPEGRepresentation()
work many times, it would help your scrolling performance if you did this work once in imageLoaderDidFinishDownloading:
and then cached it.
Since it looks like the callback happens on a background thread make sure you only manipulate the UICollectionView
from the main thread.