Last active
August 21, 2018 15:09
-
-
Save guillianbalisi/f04043339c8b8146c4073670bbc0892e to your computer and use it in GitHub Desktop.
Downloading images from a URL for a UIImageView with caching
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 { | |
/// Loads image from web asynchronosly and caches it, in case you have to load url | |
/// again, it will be loaded from cache if available | |
/// - parameter url: URL for the image | |
/// - parameter placeholder: Placeholder image to use while image is downloading, defaults to nil | |
/// - parameter template: True to use template image rendering mode, false to use original image | |
/// rendering mode, defaults to false | |
func load(url: URL, placeholder: UIImage? = nil, template: Bool = false) { | |
let cache = URLCache.shared | |
let request = URLRequest(url: url) | |
if let data = cache.cachedResponse(for: request)?.data, let image = UIImage(data: data) { | |
self.image = image.withRenderingMode(template ? .alwaysTemplate : .alwaysOriginal) | |
} 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) | |
DispatchQueue.main.async { | |
self.image = image.withRenderingMode(template ? .alwaysTemplate : .alwaysOriginal) | |
} | |
} | |
}).resume() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment