The scroll performance of my app when it downloads high resolutions images from IMGUR is slow and sluggish. Images are oddly dequeuing and rendering. Below is the code that downloads the image. I don't think the caching mechanism is working. How do I fix this?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PhotoTableViewCell", for: indexPath) as! PhotoTableViewCell
cell.descrpiptionLabel.text = photos[indexPath.row].title ?? "No Description"
cell.photoImageView.downloadImage(from: images[indexPath.row])
return cell
}
let imageCache = NSCache<NSString,AnyObject>()
extension UIImageView {
func downloadImage(from urlString: String ) {
guard let url = URL(string: urlString) else { return }
storeCache(url: url)
}
func storeCache(url:URL){
if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) as? UIImage {
self.image = cachedImage
}else {
let _: Void = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
guard let self = self else { return }
if error != nil { return }
DispatchQueue.main.async {
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: url.absoluteString as NSString)
self.image = downloadedImage
}
}
}.resume()
}
}
}
CodePudding user response:
- For your issue where the previous image is showing when the cell is reused, you should override
func prepareForReuse()
inPhotoTableViewCell
and setphotoImageView.image = nil
. - For your performance issue, it looks like you're making the API request off the main thread, so that's a good start. How large are the images you're requesting? I'm wondering if the data is so large that it's taking a lot of time to convert it to an image and then set the image on the image view