Skip to content

Instantly share code, notes, and snippets.

@Nexengineer
Last active March 5, 2019 13:44
Show Gist options
  • Save Nexengineer/d413b032aabe0478214a903d2f433458 to your computer and use it in GitHub Desktop.
Save Nexengineer/d413b032aabe0478214a903d2f433458 to your computer and use it in GitHub Desktop.
Extensions
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