【问题标题】:loading tableView images asynchronously in swift快速异步加载tableView图像
【发布时间】:2018-09-20 01:55:18
【问题描述】:

我的代码从网上下载图像并将它们设置为 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()

【问题讨论】:

  • 这个代码在 didSelectRowAtIndexPath: 中吗?
  • 不太确定,我不认为是
  • 如果您想在点击单元格时刷新数据,然后在 indexpath 处重新加载行。 tbl_name?.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 像这样.. 我认为你的代码已经在 didSelectRowAtIndexPath 方法中了。

标签: ios uitableview swift


【解决方案1】:

使用以下类:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-05
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    相关资源
    最近更新 更多