Last active
March 5, 2019 13:44
-
-
Save Nexengineer/d413b032aabe0478214a903d2f433458 to your computer and use it in GitHub Desktop.
Extensions
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
import UIKit | |
let imageCache = NSCache<AnyObject, AnyObject() | |
extension UIImageView { | |
func cacheImage(urlString: String){ | |
let url = URL(string: urlString) | |
image = nil | |
if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage { | |
self.image = imageFromCache | |
return | |
} | |
URLSession.shared.dataTask(with: url!) { | |
data, response, error in | |
if let response = data { | |
DispatchQueue.main.async { | |
let imageToCache = UIImage(data: data!) | |
imageCache.setObject(imageToCache!, forKey: urlString as AnyObject) | |
self.image = imageToCache | |
} | |
} | |
}.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment