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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.