Skip to content

Instantly share code, notes, and snippets.

@NickHung1982
Created November 3, 2017 23:49
Show Gist options
  • Save NickHung1982/2601b55d5bfd99822d48324a584b6c81 to your computer and use it in GitHub Desktop.
Save NickHung1982/2601b55d5bfd99822d48324a584b6c81 to your computer and use it in GitHub Desktop.
extension for cache download image
extension UIImageView {
func loadImageUsingCache(withUrl urlString : String) {
let url = URL(string: urlString)
self.image = nil
// check cached image
if let cachedImage = imageCache.object(forKey: urlString as NSString) as? UIImage {
self.image = cachedImage
return
}
// if not, download image from url
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async {
if let image = UIImage(data: data!) {
imageCache.setObject(image, forKey: urlString as NSString)
self.image = image
}
}
}).resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment