从UITableView单元格中的url加载异步图像 - 滚动时加载错误的图像

时间:2016-05-19 07:51:18

标签: ios swift uitableview asynchronous uiimage

我有一个tableView,可以在单元格中显示图像。大多数情况下,将显示正确的图像,但偶尔会显示错误的图像(通常是非常快速地向下滚动tableView)。我异步下载图像。

cell.profImg.getImgFromUrl(link: man.img, contentMode: cell.profImg.contentMode)

我在这里做异步请求:

extension UIImageView {
func getImgFromUrl(link link:String, contentMode mode: UIViewContentMode) {
    guard
        let url = NSURL(string: link)
        else {return}
    contentMode = mode
    NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
        guard
            let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
            let mimeType = response?.MIMEType where mimeType.hasPrefix("image"),
            let data = data where error == nil,
            let image = UIImage(data: data)
            else { return }
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.image = image
        }
    }).resume()
    }
}

1 个答案:

答案 0 :(得分:1)

我认为这是因为当您开始加载HTTP图像时,您不会重置UIImageView的内容。因此,当重复使用单元格时,将显示先前加载的图像。

您必须通过类似getImgFromUrl(如果您想要空白图片)或self.image = nil(如果您想在加载时间内获得占位符图片)的方式开始self.image = myPlaceholderImage。以下是如何将其集成到您的代码中:

extension UIImageView {
    func getImgFromUrl(link link: String, contentMode mode: UIViewContentMode) {
        guard
        self.image = nil // Here you can put nil to have a blank image or a placeholder image
        let url = NSURL(string: link)
        else { return }
        contentMode = mode
        NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
            guard
            let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
                let mimeType = response?.MIMEType where mimeType.hasPrefix("image"),
                let data = data where error == nil,
                let image = UIImage(data: data)
            else { return }
            dispatch_async(dispatch_get_main_queue()) { () -> Void in
                self.image = image
            }
        }).resume()
    }
}

但我认为你应该考虑使用SDWebImage。该库为UIImageView提供了一个类别,支持来自Web的远程图像。它会更有效,更容易。