Skip to content

Instantly share code, notes, and snippets.

@takasurazeem
Forked from amosavian/UIImageView+Cache.swift
Created November 22, 2021 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takasurazeem/de3823252be2039b0296e3315b8ea8db to your computer and use it in GitHub Desktop.
Save takasurazeem/de3823252be2039b0296e3315b8ea8db to your computer and use it in GitHub Desktop.
extension UIImageView {
/// Loads image from web asynchronosly and caches it, in case you have to load url
/// again, it will be loaded from cache if available
func load(url: URL, placeholder: UIImage?, cache: URLCache? = nil) {
let cache = cache ?? URLCache.shared
let request = URLRequest(url: url)
if let data = cache.cachedResponse(for: request)?.data, let image = UIImage(data: data) {
self.image = image
} else {
self.image = placeholder
URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if let data = data, let response = response, ((response as? HTTPURLResponse)?.statusCode ?? 500) < 300, let image = UIImage(data: data) {
let cachedData = CachedURLResponse(response: response, data: data)
cache.storeCachedResponse(cachedData, for: request)
self.image = image
}
}).resume()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment