Last active
March 11, 2020 13:54
-
-
Save malcolmkmd/56cf202401344cf0496ab6b8edf5e0c1 to your computer and use it in GitHub Desktop.
SwiftBits: Caching Images
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
public extension UIImageView { | |
public func loadImage(fromURL url: String) { | |
guard let imageURL = URL(string: url) else { | |
return | |
} | |
let cache = URLCache.shared | |
let request = URLRequest(url: imageURL) | |
DispatchQueue.global(qos: .userInitiated).async { | |
if let data = cache.cachedResponse(for: request)?.data, let image = UIImage(data: data) { | |
DispatchQueue.main.async { | |
self.transition(toImage: image) | |
} | |
} else { | |
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.transition(toImage: image) | |
} | |
} | |
}).resume() | |
} | |
} | |
} | |
public func transition(toImage image: UIImage?) { | |
UIView.transition(with: self, duration: 0.3, | |
options: [.transitionCrossDissolve], | |
animations: { | |
self.image = image | |
}, | |
completion: nil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment