David Henry
David Henry

Reputation: 3046

Setting Image from SDWebImage on UITableView Reload

I have a list of cells within a UITableView. The images are being downloaded by the following method inside the cell

self.profileImage.sd_setImage(with: URL(string: profileURL), completed: { (image, error, cache, url) in
                            if image != nil {
                                self.profileImage.image = image
                            } else {
                                print("didn't load image")
                            }
                        })

However, upon reloading and resorting the UITableView the previous image for that index is loaded for a brief moment and then after that the updated image for that index appears.

Now my theory is the following happens (correct me if I'm wrong)...

  1. The image is downloaded as soon as the URL is retrieved.
  2. That image is cached with SDWebImage.
  3. TableView reloads and data in cells change.
  4. SDWebImage uses the cached image for that indexPath instead of the cell. (Problem here)
  5. SDWebImage downloads the URL again for that cell and refreshes the image.

If this is correct what I need is to do the following...

  1. Download image as soon as the URL is retrieved.
  2. Cache the image with SDWebImage.
  3. TableView reloads and data in cells change.
  4. Use the cached image for that cell.

Am I using the wrong method for setting the self.profileImage?

As always any help is greatly appreciated.

Upvotes: 0

Views: 2519

Answers (2)

AlexSmet
AlexSmet

Reputation: 2161

If you configure your cells using UITableViewCell, than you can override method prepareForReuse() for clearing old images, for example:

override func prepareForReuse() {
    super.prepareForReuse()
    profileImage.image = nil
}

By this way old cached images won't be appear.

Upvotes: 0

Majed Dkahellalah
Majed Dkahellalah

Reputation: 408

1.Download image as soon as the URL is retrieved. 2.Cache the image with SDWebImage.

you use this code

let url = NSURL(string: "https://test.com/upload/image.jpg")!

self.imageD.sd_setImage(with: url as URL!, placeholderImage: UIImage(named: "default_logo"), options: .transformAnimatedImage, progress: nil, completed: nil)

this default_logo put inside Assets.xcassets

3.TableView reloads and data in cells change.

self.tableView.reloadData()

Upvotes: 1

Related Questions