简体   繁体   中英

Cancel request for Alamofire image

Basic Information: I have a tableView and each tableView cell containing an image and few labels . I use tableView prefetch data method to make API calls to fetch data as the tableView scrolls.

Issue: Sometimes I see a particular cell showing an image of some other cell . This happens when I scroll a little faster than normal speed. Note: In order to overcome from this issue I just need to scroll the tableView up/down

Things tried: I have set the imageView to nil in prepare for reuse method.

The conclusion I have reached: By debugging the issue I understood that once a cell is visible I make an image request using Alamofire Image but I scroll it before we received the response. So, what might be happening is that on receiving a response it is setting an image for the cell but that cell is not visible as I am reusing the cells. The cell contains some other data.

Please let me know how can I cancel the request if the cell is not visible. Let me know if I am missing something in the question.

This is happening because tableView reuse the cells and if it having a image downloading in queue and you scroll and the downloading is complete, it shows the downloaded image for few second until correct image download.

use placeholder in af_setImage method. it will solve your problem

imageView.af_setImage(withURL: URL(string: img)!, placeholderImage: UIImage(named: "product_placeholder")

What I do in this situation is set the cell's tag to match the row number.

When the image requests complete, I check if it still has the same tag (if it was reused, tag would be changed).

Something like this, in cellForRowAt indexPath :

cell.tag = indexPath.row
ImageService.shared.getImage(completion: { (image) in
  if let image = image, cell.tag == indexPath.row {
    //apply image
  }
}

This doesn't cancel the request, but it ignores the result if the cell is not in the same position anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM