ios - Swift 图片下载 TableView

标签 ios swift image uitableview download

我正在尝试解决在 Swift 的 TableView 中异步下载图像的问题。这是我的问题:我从 url 异步下载图像,但如果我快速滚动 TableView,我的图片开始旋转。(图像交替出现,直到出现正确的图像)。

这是我下载的异步代码和 imageCache

let imageCache = NSCache()

//DOWNLOAD Image ASINC
extension UIImageView {

    public func imageFromServerURL(url: String){

        if(imageCache.objectForKey(url) != nil){
            self.image = imageCache.objectForKey(url) as? UIImage
        }else{

            let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
            let task = session.dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, response, error) -> Void in
                if error == nil {

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        if let downloadedImage = UIImage(data: data!) {
                            imageCache.setObject(downloadedImage, forKey: url)
                            self.image = downloadedImage
                        }
                    })

                }
                else {
                    print(error)
                }
            })
            task.resume()
        }

    }
}

我记得在 TableView 中是这样的:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("record_charts", forIndexPath: indexPath) as! myTableViewCell

            let url_img = "https://image/download.jpg"
            cell.immagine.imageFromServerURL(url_img)


        return cell
    }

这是更好地向您展示问题的gif Gif Problem

最佳答案

这得益于iOS的table view的复用机制。 您可以对代码进行一些修改以解决此问题:

class AsyncImageView: UIImageView {

private var currentUrl: String? //Get a hold of the latest request url

public func imageFromServerURL(url: String){
    currentUrl = url
    if(imageCache.objectForKey(url) != nil){
        self.image = imageCache.objectForKey(url) as? UIImage
    }else{

        let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
        let task = session.dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, response, error) -> Void in
            if error == nil {

                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    if let downloadedImage = UIImage(data: data!) {
                        if (url == currentUrl) {//Only cache and set the image view when the downloaded image is the one from last request
                            imageCache.setObject(downloadedImage, forKey: url)
                            self.image = downloadedImage
                        }

                    }
                })

            }
            else {
                print(error)
            }
        })
        task.resume()
    }

}
}

注意#1:我在白板上对修改进行编码,所以不确定代码的语法是否正确。

注意 #2:您可以使用关联 对象,而不是声明 UIImageView 的新子类。

注意 #3:我强烈建议您使用 AlamoFireImage,它有一个 UIImageView 类别,这正是您在这种情况下(以及 future 的情况下)所需要的。

关于ios - Swift 图片下载 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44393183/

相关文章:

ios - 将 pdf 第一页转换为 Collection View 单元格时创建黑框的代码。如何解决这个问题?

ios - 应用内购买 appStoreReceiptURL 为空

swift - 在主应用程序发布的 Today Widget 中观察通知

swift - 快速处理 json 响应 Observable

c# - 仅打印嵌入到 ASP.NET 页面中的图像

ios - 如果用户禁用密码,如何对 iOS 数据保护使用react?

ios - 在正确的地方调用 reloadData()

ios - 子类化具有 xib 的子类化 UIViewController

php - 如何使用 ffmpeg 和 PHP 创建图像?

html - Cocoa WebView 不会在 OSX 10.8 上渲染所有图像