0

I have a table in swift. Whenever I scroll up and down the tableview it runs the getImageForCell function again even though the image has already been loaded. Is there a way for this not to happen. Below is my code.

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

    let review = json[reviewType][indexPath.row]
    cell.nameLabel.text = review[userType]["name"].stringValue
    cell.reviewLabel.text = review["message"].stringValue
    cell.dateLabel.text = review["created_at"].stringValue
    cell.ratingStars.rating = Double(review["rating"].intValue)
    getImageForCell(url: review[userType]["photo_url"].stringValue, cell: cell)

    return cell
}

func getImageForCell(url: String, cell: ReviewTableViewCell) {
    Alamofire.request(url).responseImage { response in
        if let downloadedImage = response.result.value {
            print("downloaded image \(downloadedImage)")
            DispatchQueue.main.async {
                cell.profileImageView.image = downloadedImage
            }
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Rob
  • 6,758
  • 4
  • 46
  • 51
  • "Is there a way for this not to happen" What's an alternative that you wish to happen? – El Tomato Oct 10 '17 at 01:56
  • He means he doesn't want the image to have to download each time, but to use a cached image to avoid the network call. – stktrc Oct 10 '17 at 01:57
  • check this link: https://stackoverflow.com/questions/45316099/nscache-doesnt-work-with-all-images-when-loading-for-the-first-time – 3stud1ant3 Oct 10 '17 at 02:06
  • https://github.com/rs/SDWebImage This library provides an async image downloader with cache support. – Nishant Bhindi Oct 10 '17 at 04:28

1 Answers1

0

This is due to both not cacheing the image, and also not reusing the cell - in your view you are recreating the cell each time - this would not specifically fix the image issue, but will improve performance. My favourite cache image extension is kingfisher (no affiliation), although alamofire can be used to cache images too.

https://github.com/onevcat/Kingfisher

stktrc
  • 1,599
  • 18
  • 30