WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: UITableView Pagination

Forums > iOS

Hi friends

I'm a little lost about the behaviour of the tableView, more especific, pagination per request.

In the case of the code bellow, the request to get the images happens only for the images that are actually showing on the screen, correct?

Or it's making some other kind of request in background that i didn't understand yet?

import UIKit

let imageCache = NSCache<AnyObject, AnyObject>()

class CustomImageView: UIImageView {
    var task: URLSessionTask!

    func loadImage(from url: URL) {
        image = nil // Isso é para resetar o estado da cell, assim ela aparece em branco ao invés de com cache da imagem antes do Dequeue

        if let task = task {
            task.cancel()
        }

        if let imageFromCache = imageCache.object(forKey: url.absoluteString as AnyObject) as? UIImage {
            self.image = imageFromCache
            return
        }

        task = URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data, let newImage = UIImage(data: data) else {
                print("Couldn't lead the image from  \(url)")
                return
            }

            imageCache.setObject(newImage, forKey: url.absoluteString as AnyObject)

            DispatchQueue.main.async {
                self.image = newImage
            }
        }

        task.resume()
    }
}

I now the caching will improve for lesser requests, but I fear that maybe I missed something.

PS almost forgot, is there any way to use the images from cache to make a FavoritesList for example? Or the cache cleans at the session end(or closing the app)

1      

Hi,

I would 100% recommend to use library here. For example Nuke or Kingfisher. Then you start the download request in the cellForRowAt and cancel it in prepareForReuse to not download images that are no longer visible.

2      

Thanks, will look for this libs right now.

1      

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.