How can I download and show images first in the visible cells from URL quickly and prefetch for next cells?

239 Views Asked by At

I have to display multiple images in a UICollectionView that contains small logos. When the page is loaded, I want to show logos instantly like in Netflix or any other app, and when I scroll down, the images are shown instantly too. I'm using the Kingfisher library to download images from the URL in my UICollectionViewCell, but I'm open to accept any other approach that is better.

After hitting the API, when I reload the UICollectionView with the response data, I display images like this:

static let p = ResizingImageProcessor(referenceSize: .init(width: 100, height: 100), mode: .aspectFit) // Processor to resize image to 100 * 100 so download is faster

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return carModels.count
}
    
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"CarModelCollectionViewCell", for: indexPath) as! CarModelCollectionViewCell
        
    let data = carModels[indexPath.row]
        
    cell.ivCar.kf.indicatorType = .activity // added this later as images were taking long to download
    cell.ivCar.kf.setImage(with: data.image, options: [.downloadPriority(1),.processor(CarModelViewController.p), .transition(.fade(0.2))])
        
    return cell
}
    
func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
    var carLogoUrlArray = [URL]()
    for indexPath in indexPaths {
        guard let url = carModels[indexPath.row].image else { return }
        carLogoUrlArray.append(url)
    }
    ImagePrefetcher(urls: carLogoUrlArray, options: [.processor(CarModelViewController.p), .downloadPriority(0.75)]).start()
}

When I run this code, it still takes too long to download images as images start downloading after the UICollectionView is reloaded. Is there any way to make the download faster using the Kingfisher library or any other library?

Also prefetching seems to work fine but is it the correct way to download URLs in advance?

My code gets the job done, but I would like to have images downloaded instantly like Netflix or Twitter, where even high quality images are downloaded instantly.

1

There are 1 best solutions below

1
alessandro_minopoli On

You may use

.cacheOriginalImage as one of the options given to Kingfisher

and

placeholder as an added parameter to the setImage