Last active
January 12, 2020 14:33
-
-
Save nitin-agam/442f6f72b0c9c5f60d446a8833d7d1d6 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
import UIKit | |
let imageCache = NSCache<AnyObject, AnyObject>() | |
extension UIImageView { | |
func loadImage(urlString: String) -> Void { | |
if urlString.isEmpty { return } | |
self.image = nil | |
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage { | |
self.image = cachedImage | |
return | |
} | |
guard let url = URL(string: urlString) else { return } | |
let request = URLRequest(url: url) | |
let dataTask = URLSession.shared.dataTask(with: request) {data, response, error in | |
if error != nil { return } | |
DispatchQueue.main.async { | |
let downloadedImage = UIImage(data: data!) | |
if let image = downloadedImage { | |
imageCache.setObject(image, forKey: urlString as AnyObject) | |
self.image = UIImage(data: data!) | |
} | |
} | |
} | |
dataTask.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment