I'm trying to cache images from a URL to make my table scroll more smoothly. This doesn't seem to be caching them and I can't figure out what I'm doing wrong. Can anyone tell me what's wrong with this?
let imageCache = NSCache()
extension UIImageView {
func loadImageUsingCacheWithUrlString(urlString: String) {
self.image = nil
//check cache for image first
if let cachedImage = imageCache.objectForKey(urlString) as? UIImage {
self.image = cachedImage
return
}
//otherwise fire off a new download
let url = NSURL(string: urlString)
NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) in
//download hit an error so lets return out
if error != nil {
print(error)
return
}
dispatch_async(dispatch_get_main_queue(), {
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: urlString)
self.image = downloadedImage
}
})
}).resume()
}
}
I feel like there should be an else { before firing off the new download, but even when I tried that I don't think it was working right. I even tried running it this way, scrolling through the table to make sure it has a chance to cache all the images, then deleting the whole download part so that it will only load cached images, and no images showed up so I don't think it's actually caching them.