1

When I scroll my UITableView quickly, imageView shows the wrong images from API. (i.e. Samsung image shown in Brexit article and so on).

Here`s an extension allowing me to download images(maybe I can change something here):

extension UIImageView {
    func donwloadImage(from url: String) {
        let urlRequest = URLRequest(url: URL(string: url)!)
        let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

            if error != nil {
                print(error)
                return
            }

            DispatchQueue.main.async {
                self.image = UIImage(data: data!)

            }
        }
        task.resume() 
    }

}
Mohit Kumar
  • 2,898
  • 3
  • 21
  • 34
Russ
  • 99
  • 1
  • 7
  • why don't you use 3rd party lib for this? If you want I can give you links of few libs. – Mohit Kumar Jan 31 '20 at 09:30
  • Yes, maybe i can give it a try, thank you! – Russ Jan 31 '20 at 09:33
  • There should be no need to use a third-party dependency for something like this - you're just complicating your code base for no good reason. Without seeing the tableView code we can't be certain, but it's almost definitely due to the image download being async and not quick enough for fast scrolling, so it shows the image from the last time the cell was used. Consider clearing the previous image or setting a default in `cellForRowAt` or pre-caching images. – flanker Jan 31 '20 at 10:08

3 Answers3

0

Try any of the following lib:

https://github.com/SDWebImage/SDWebImage

https://github.com/onevcat/Kingfisher

Mohit Kumar
  • 2,898
  • 3
  • 21
  • 34
0

Below is the example that shows correct handling. Please have a try.


class CustomViewCell: UITableViewCell {

@IBOutlet weak var imageView: UIImageView!

private var task: URLSessionDataTask?

override func prepareForReuse() {
    super.prepareForReuse()
    task?.cancel()
    imageView.image = nil
}

func configureWith(url string: String) {
    guard let url = URL(string: string) else { return }

    task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let data = data, let image = UIImage(data: data) {
            DispatchQueue.main.async {
                self.imageView.image = image
            }
        }
    }
    task?.resume()
 }
}
Mayank
  • 315
  • 2
  • 13
0

definitely use a library for this.

advice

https://github.com/kean/Nuke

nuke is very simple.

Nuke.loadImage(with: url, into: imageView)
g89n7man
  • 59
  • 1
  • 1
  • 6