There is a table in which besides the text there are pictures in each cell. There are about 3,000 positions in the table, pictures are loaded by url, which I get through parsing. With a bad Internet or fast scrolling of the table, images overlap, I think you know this problem, when in one cell the picture quickly changes until it reaches its turn on the index. What to do in this case? I searched for a long time, tried many things (except for libraries, for for some reason none of them is installed correctly)

UPD:

At the moment, the cells are formed as follows:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableViewCellAdd cell.imageAdd.downloaded(from: filteredData[indexPath.row].ima) } 

Thanks to this extension:

 extension UIImageView { func downloaded(from url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) { contentMode = mode URLSession.shared.dataTask(with: url) { data, response, error in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let data = data, error == nil, let image = UIImage(data: data) else { return } DispatchQueue.main.async() { self.image = image } }.resume() } func downloaded(from link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) { guard let url = URL(string: link) else { return } downloaded(from: url, contentMode: mode) } 

}

  • one
    Need an example, working with cells is wrong. - VAndrJ
  • I apologize that with such a delay, I updated the post with how I form the cells. The picture is downloaded by url, from the array with these url - Vladislav Bublik

2 answers 2

That's the reason for all the trouble - you run dataTask , but the cells are reused. Accordingly, the first picture for a cell can be downloaded later than the next, which are downloaded when reused. Need to cancel the task.

I also advise using the excellent Kingfisher library .

  • I try to do without libraries, for problems with installing them. I nullify the picture in the method - func prepareForReuse {cell.imageAdd.image = nil; } but apparently this is not enough - Vladislav Bublik
  • @VladislavBublik What are the difficulties with libraries? - VAndrJ
  • Yes, it made mistakes, even created a separate topic, now everything seems to be working, installed Kingfisher - Vladislav Bublik

Use URLSessionDownloadTask in the cell

 var downloadTask: URLSessionDownloadTask? override func prepareForReuse() { super.prepareForReuse() downloadTask?.cancel() downloadTask = nil } downloadTask = download image