0

As I scroll throughout the tableView the images flicker in and out even though there is a cache implemented.

let imageCache = NSCache<NSString, UIImage>()

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Reuse", for: indexPath) as! TableViewCell

    if var downloadURL = URL(string: self.imageURLS[indexPath.row]) {
        //cell.cellImageView.contentMode = .scaleAspectFit
        // add constraints x,y, width and height

        if var image = imageCache.object(forKey: self.imageURLS[indexPath.row] as NSString) {
            cell.cellImageView.image = image
        } else {         
            URLSession.shared.dataTask(with: downloadURL!, completionHandler: {(data,response,error) in

                if error != nil {
                    print(error!)
                    return
                }
                let downloadedImage = UIImage(data:data!)
                self.imageCache.setObject(downloadedImage!, forKey: (downloadURL?.absoluteString as NSString?)!)
                DispatchQueue.main.async {
                    cell.cellImageView.image = downloadedImage
                    cell.cellImageView.image?.resizeImageWith()
                    tableView.beginUpdates()
                    tableView.endUpdates()
                }
            }).resume()
        }
        return cell
    }
    return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    tableView.estimatedRowHeight = 500.0
    return UITableViewAutomaticDimension
}
Jay Patel
  • 2,642
  • 2
  • 18
  • 40
user372382
  • 183
  • 9

0 Answers0