有没有办法在用户每次打开应用程序时不重新下载图像?
Is there a way to not redownload images everytime a user opens the app?
我正在开发一个显示图像的 tableView,它会在每次加载视图时重新下载图像。有没有办法缓存图像以便它只下载一次图像? (缓存图片)
你可以这样做:
在你的 tableViewDelegate 中创建一个缓存对象
var myCache = NSCache()
然后在rowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let row = tableView.dequeueReusableCellWithIdentifier("MyCell") as? MyCell{
//Get the item
let item = items[indexPath.row]
//You need to cancel previous requests and reset the image to avoid render errors caused by the reusable row
//here you should also cancel any previous requests made to avoid downloading an image that the user won't see because he scrolled
cell.img.image = nil
//Search for the image in the cache
var img:UIImage?
img = myCache.objectForKey(item.image_url) as? UIImage
row.configureCell( item: item,img:img)
return row
}else{
return MyCell()
}
}
最后在单元格中
func configureCell(item:Item,image:UIImage?){
self.item = item
if image != nil{
//The image exist so you assign it to your UIImageView
img.image = image
}else{
//Create the request to download the image
}
}
我正在开发一个显示图像的 tableView,它会在每次加载视图时重新下载图像。有没有办法缓存图像以便它只下载一次图像? (缓存图片)
你可以这样做:
在你的 tableViewDelegate 中创建一个缓存对象
var myCache = NSCache()
然后在rowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let row = tableView.dequeueReusableCellWithIdentifier("MyCell") as? MyCell{
//Get the item
let item = items[indexPath.row]
//You need to cancel previous requests and reset the image to avoid render errors caused by the reusable row
//here you should also cancel any previous requests made to avoid downloading an image that the user won't see because he scrolled
cell.img.image = nil
//Search for the image in the cache
var img:UIImage?
img = myCache.objectForKey(item.image_url) as? UIImage
row.configureCell( item: item,img:img)
return row
}else{
return MyCell()
}
}
最后在单元格中
func configureCell(item:Item,image:UIImage?){
self.item = item
if image != nil{
//The image exist so you assign it to your UIImageView
img.image = image
}else{
//Create the request to download the image
}
}