在swift中异步加载tableView图像 [英] loading tableView images asynchronously in swift

查看:141
本文介绍了在swift中异步加载tableView图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My code download images from the web and sets them as a tableView cell imageView. It works fine except that I need to tap on a cell for it to refresh the cell's content and load the image. I would like the images to appear as soon as they are loaded. I have tried adding reloadData() under cellToUpdate but the app eventually gets stuck in an infinite loop and crashes. This is my code:

        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()


推荐答案

使用以下类:

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")

这篇关于在swift中异步加载tableView图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆