ios - NSCache 在 Swift 中为 UITableView 存储图像

标签 ios uitableview swift nscache

我是 swift 编程的新手,我搜索了很多有关使用 Swift 使用 NSCache 存储图像的信息。

到目前为止,我所做的是使用 JSON 获取 idimageName,并且我的数据在数组中,并且能够显示图像在细胞中没有问题。现在我想缓存图像。 这是我编写的代码:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as TableViewCell

        //cell.imageView
         nameID = self.hoge[indexPath.row]["cars"]["carid"].string!
        cell.nameLabel.text = nameID

        if let imageFileURL = imageCache.objectForKey(self.hoge[indexPath.row]["cars"]["carid"].intValue) as? NSURL {
            println("Get image from cache")

        } else {

            imageName = self.hoge[indexPath.row]["cars"]["pic_name"].string!

            // If the image does not exist, we need to download it
            var imgURL: NSURL = NSURL(string: "http://192.168.1.35/car/uploads/" + imageName )!

            var image:UIImage = UIImage(named: "pen")!
            // Download an NSData representation of the image at the URL
            let request: NSURLRequest = NSURLRequest(URL: imgURL)
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
                if error == nil {
                    image = UIImage(data: data)!
                    cell.viewCell.image = image

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

        }

        return cell
    }

那么,如何使用缓存存储和检索图像?

最佳答案

我建议你去看看这个图书馆HanekeSwift (它为 UIImage、NSData、JSON、String 或任何其他可以作为数据读取或写入的类型提供了内存和 LRU 磁盘缓存),至少了解它们是如何处理缓存的,您可以决定使用它或创建您自己的解决方案。

使用非常容易/简单的 API:

// Setting a remote image
imageView.hnk_setImageFromURL(url)

// Setting an image manually. Requires you to provide a key.
imageView.hnk_setImage(image, key: key)

使用缓存

let cache = Shared.dataCache

cache.set(value: data, key: "image.png")

// Eventually...

cache.fetch(key: "image.png").onSuccess { data in
     // Do something with data
}

关于ios - NSCache 在 Swift 中为 UITableView 存储图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29004336/

相关文章:

ios - 为 UIRefreshControl 提供顶部插图

json - Swift 4 将数据从 json 保存到数组以在 TableView 中显示

objective-c - Interface Builder 有没有办法渲染不覆盖 drawRect : 的 IBDesignable View

ios - 获取在 WKWebView 中点击的链接 URL

iphone - AFNetworking - 构建 NSDictionary 参数

ios - 无法使用参数列表类型(字符串 : String, 属性 : [NSObject: AnyObject]?)调用 NSAttributedString 类型的初始值设定项

ios - Xcode - 启动 WatchKit 扩展时出错

ios - 为什么 UITableView 在重新加载数据时会缓存单元格?

iphone - 模糊 UILabel 作为 UITableViewCell contentView 的编程 subview

ios - 正确使用 MKLocalSearch CompletionHandler