NEW: Learn to build the incredible iOS 15 Weather app today! >>

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)

   

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.

1      

Thanks, will look for this libs right now.

   

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS, you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Learn More

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

Reply to this topic…

You need to create an account or log in to reply.

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.