[英]Cancel request for Alamofire image
Basic Information: I have a tableView and each tableView cell containing an image and few labels . 基本信息:我有一个tableView,每个tableView单元格都包含一个图像和几个标签 。 I use tableView prefetch data method to make API calls to fetch data as the tableView scrolls.
我使用tableView prefetch data方法进行API调用,以在tableView滚动时获取数据。
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
注意:为了克服这个问题,我只需要向上/向下滚动tableView
Things tried: I have set the imageView to nil in prepare for reuse method. 尝试过的事情:在准备重用方法时,我将imageView设置为nil。
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. 我得出的结论是:通过调试问题,我了解到,一旦看到一个单元格,便可以使用Alamofire Image发出图像请求,但是在收到响应之前会对其进行滚动。 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. 发生这种情况是因为tableView重用了单元格,并且如果队列中有图像下载并且您滚动并且下载完成,它将显示下载的图像几秒钟,直到正确的图像下载为止。
use placeholder in af_setImage
method. 在
af_setImage
方法中使用占位符。 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
: 在
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. 这不会取消请求,但是如果单元格不再位于同一位置,它将忽略结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.