Last active
November 12, 2018 23:09
-
-
Save zmcartor/db2e89211d69f6760d65f0430b460952 to your computer and use it in GitHub Desktop.
UIImageView load from URL, placeholder and cache
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 setImage(from url: URL, withPlaceholder placeholder: UIImage? = .none, withCache cache:NSCache<NSURL,UIImage>? = .none) -> URLSessionDataTask? { | |
if let cached = cache?.object(forKey: url as NSURL) { | |
self.image = cached | |
return .none | |
} | |
self.image = placeholder | |
let task = URLSession.shared.dataTask(with: url) { (data, _, _) in | |
if let data = data, let image = UIImage(data: data) { | |
cache?.setObject(image, forKey: url as NSURL) | |
DispatchQueue.main.async { | |
self.image = image | |
} | |
} | |
} | |
task.resume() | |
return task | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment