Created
November 3, 2017 23:49
-
-
Save NickHung1982/2601b55d5bfd99822d48324a584b6c81 to your computer and use it in GitHub Desktop.
extension for cache download image
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
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