use*_*956 1 uitableview ios nscache swift
我是swift编程的新手,我已经搜索了很多关于使用Swift存储NSCache图像的方法.
到目前为止我所做的是,我正在使用JSON 获取ids和imageNames,我将数据存储在数组中,并且能够在单元格中显示图像而没有任何问题.现在我想缓存图像.这是我写的代码:
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
}
Run Code Online (Sandbox Code Playgroud)
那么,如何使用缓存存储和检索图像?
我建议你检查这个库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)
Run Code Online (Sandbox Code Playgroud)
使用缓存
let cache = Shared.dataCache
cache.set(value: data, key: "image.png")
// Eventually...
cache.fetch(key: "image.png").onSuccess { data in
// Do something with data
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5700 次 |
| 最近记录: |