Last active
April 19, 2018 15:00
-
-
Save fethica/44cc52e0f0bd16a3a7f61bc8a4a6f086 to your computer and use it in GitHub Desktop.
A simple thumbnail (small) image loader that support 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
class ImageLoader { | |
private let cache = NSCache<NSString, NSData>() | |
class func image(for url: URL, completionHandler: @escaping(_ image: UIImage?) -> ()) { | |
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { | |
if let data = self.cache.object(forKey: url.absoluteString as NSString) { | |
DispatchQueue.main.async { completionHandler(UIImage(data: data as Data)) } | |
return | |
} | |
guard let data = NSData(contentsOf: url) else { | |
DispatchQueue.main.async { completionHandler(nil) } | |
return | |
} | |
self.cache.setObject(data, forKey: url.absoluteString as NSString) | |
DispatchQueue.main.async { completionHandler(UIImage(data: data as Data)) } | |
} | |
} | |
} | |
// Usage: | |
ImageLoader.image(for: imageURL) { image in | |
self.imageView.image = image | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment