Skip to content

Instantly share code, notes, and snippets.

@iksnae
Last active July 26, 2016 14:17
Show Gist options
  • Save iksnae/28caf99827a9770f40c241e7e43ed7ae to your computer and use it in GitHub Desktop.
Save iksnae/28caf99827a9770f40c241e7e43ed7ae to your computer and use it in GitHub Desktop.
class ImageCache {
static let shared = ImageCache()
let cache: NSCache<NSString,UIImage> = NSCache()
func addImage(key:String, image:UIImage) {
self.cache.setObject(image, forKey: key)
}
func getImage(key:String) -> UIImage? {
return self.cache.object(forKey: key)
}
func fetchImage(url:NSURL, callback:(image:UIImage?)->()) {
NSURLSession.shared().dataTask(with: url) { (data:NSData?, response:NSURLResponse?, error:NSError?) in
guard
let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType where mimeType.hasPrefix("image"),
let data = data where error == nil,
let image = UIImage(data: data)
else {
callback(image: nil)
return
}
self.addImage(key: url.absoluteString, image: image)
callback(image: image)
}.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment