Reputation: 787
I'm working on a tableView that shows images and it is re-downloading the images every time the view loads. Is there a way to cache the images so it only downloads the images once? (Cache the images)
Upvotes: 0
Views: 343
Reputation: 2533
You can do this:
In your tableViewDelegate create a Cache object
var myCache = NSCache()
Then in the 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()
}
}
And finally in the cell
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
}
}
Upvotes: 1