在swift中异步加载tableView图像

时间:2014-10-12 11:04:32

标签: ios uitableview swift

我的代码从网上下载图片并将它们设置为tableView单元格imageView。它工作正常,除了我需要点击一个单元格来刷新单元格的内容并加载图像。我希望这些图像在加载后立即显示。我尝试在cellToUpdate下添加reloadData(),但应用程序最终陷入无限循环并崩溃。这是我的代码:

        let request: NSURLRequest = NSURLRequest(URL: imgURL)
        let getImage: NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
            if error == nil {
                                    image = UIImage(data: data)

                                    // Store the image in to our cache
                                    self.imageCache[urlString] = image
                                    dispatch_async(dispatch_get_main_queue(), {
                                        if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
                                            cellToUpdate.imageView?.image = image


                                        }
                                    })
                                }
                                else {
                                    println("Error: \(error.localizedDescription)")
                                }
                            })
        getImage.resume()

1 个答案:

答案 0 :(得分:10)

使用以下课程:

class ImageLoadingWithCache {

    var imageCache = [String:UIImage]()

    func getImage(url: String, imageView: UIImageView, defaultImage: String) {
        if let img = imageCache[url] {
            imageView.image = img
        } else {
            let request: NSURLRequest = NSURLRequest(URL: NSURL(string: url)!)
            let mainQueue = NSOperationQueue.mainQueue()

            NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
                if error == nil {
                    let image = UIImage(data: data)
                    self.imageCache[url] = image

                    dispatch_async(dispatch_get_main_queue(), {
                        imageView.image = image
                    })
                }
                else {
                    imageView.image = UIImage(named: defaultImage)
                }
            })
        }
    }
}

用法:

var cache = ImageLoadingWithCache()
cache.getImage(YOUR_URL, imageView: YOUR_IMAGEVIEW, defaultImage: "DEFAULT_IMAGE_NAME")