Skip to content

Instantly share code, notes, and snippets.

@zmcartor
Last active November 12, 2018 23:09
Show Gist options
  • Save zmcartor/db2e89211d69f6760d65f0430b460952 to your computer and use it in GitHub Desktop.
Save zmcartor/db2e89211d69f6760d65f0430b460952 to your computer and use it in GitHub Desktop.
UIImageView load from URL, placeholder and cache
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