UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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)

3      

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.

4      

Thanks, will look for this libs right now.

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.