Baixe e armazene em cache imagens no UITableViewCell
Nota: Por favor, não há bibliotecas. Isso é importante para eu aprender. Além disso, há uma variedade de respostas sobre isso, mas nenhuma que eu encontrei resolve o problema muito bem. Por favor, não marque como duplicado. Desde já, obrigado!
O problema que tenho é que, se você rolar muito rápido na tabela, verá imagens antigas e tremeluzentes.
A solução das perguntas que li é cancelar oURLSession
pedido de data. Mas não sei como fazer isso no lugar e hora corretos. Pode haver outras soluções, mas não tenho certeza.Isto é o que eu tenho até agora:
Classe de cache de imagem
class Cache {
static let shared = Cache()
private let cache = NSCache<NSString, UIImage>()
var task = URLSessionDataTask()
var session = URLSession.shared
func imageFor(url: URL, completionHandler: @escaping (image: Image? error: Error?) -> Void) {
if let imageInCache = self.cache.object(forKey: url.absoluteString as NSString) {
completionHandler(image: imageInCache, error: nil)
return
}
self.task = self.session.dataTask(with: url) { data, response, error in
if let error = error {
completionHandler(image: nil, error: Error)
return
}
let image = UIImage(data: data!)
self.cache.setObject(image, forKey: url.absoluteString as NSString)
completionHandler(image: image, error: nil)
}
self.task.resume()
}
}
Uso
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let myImage = images[indexPath.row]
if let imageURL = URL(string: myImage.urlString) {
photoImageView.setImage(from: imageURL)
}
return cell
}
Alguma ideia?