I have developed an app which shows "full screen cards" in a UICollectionView
like Tinder. The card contains an image and some text. I was loading the image using SDWebImage
's sd_setImageWithURL
method in the UICollectionView
's cell.
However this was not giving me good performance since the images were mostly loaded when the user was on a card. I therefore used the SDWebImagePrefetcher
prefetch queue to do this as follows:-
func startImagePreloadingOperationForIndex(index:Int)
{
let numberOfImagesToBePreloadedOnEachSide = 20
var previousIndex = index - numberOfImagesToBePreloadedOnEachSide
var nextIndex = index + numberOfImagesToBePreloadedOnEachSide
if previousIndex < 0
{
previousIndex = 0
}
if nextIndex >= currentNewsCollection.count
{
nextIndex = currentNewsCollection.count - 1
}
if previousIndex >= nextIndex || currentNewsCollection.isEmpty
{
return
}
let arrayOfNewsStories = currentNewsCollection[previousIndex...nextIndex]
let arrayOfImageURLs = arrayOfNewsStories.map( { ImageUtility.getImageStringForNewsStory($0) } )
SDWebImagePrefetcher.sharedImagePrefetcher().prefetchURLs(arrayOfImageURLs, progress: { (x, y) -> Void in
}) { (x, y) -> Void in
}
}
This function is called when the user lands on a particular card. The prefetching queue automatically manages not downloading images in cache so I don't have to worry about that. Along with this I am also using the sd_setImageWithURL
in cellForItemAtIndexPath
to pick up the downloaded image from the cache.
This is a better solution since I am now preloading images when the user is on a card. However this is a parallel queue. Which means image no. index + 20 could be loaded before the current image and the user could have to wait for the image. Also the app becomes a bit laggy if the user scrolls through over 50 cards and the memory usage also keeps on going up.
Can anyone please suggest improvements to this or a better algorithm?
Thanks