Last active
July 26, 2016 14:17
-
-
Save iksnae/28caf99827a9770f40c241e7e43ed7ae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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