Skip to content

Instantly share code, notes, and snippets.

@kittisak-phetrungnapha
Last active October 29, 2018 18:45
Show Gist options
  • Save kittisak-phetrungnapha/0464e32ec38b5b45cc2b44e118a65ec0 to your computer and use it in GitHub Desktop.
Save kittisak-phetrungnapha/0464e32ec38b5b45cc2b44e118a65ec0 to your computer and use it in GitHub Desktop.
This is Swift 3 image downloader manager (uses Kingfisher) supported with cache that uses image's string url for key.
import Foundation
import Kingfisher
struct ImageDownloadManager {
static let shared = ImageDownloadManager()
private init() {}
// MARK: - Public method
func fetchImage(with imageUrl: String, completion: @escaping (UIImage?) -> Void) {
// Check if cache is existing.
if checkImageCache(with: imageUrl) {
fetchImageFromCache(with: imageUrl, completion: { (image: Image?) in
completion(image)
})
return
}
// Download image from url.
download(from: imageUrl) { (image: Image?) in
if let image = image {
// Save image to cache
self.saveImageToDisk(with: image, key: imageUrl)
completion(image)
return
}
completion(nil)
}
}
// MARK: - Private method
private func checkImageCache(with key: String) -> Bool {
return ImageCache.default.isImageCached(forKey: key).cached
}
private func fetchImageFromCache(with key: String, completion: @escaping (Image?) -> Void) {
ImageCache.default.retrieveImage(forKey: key, options: nil) {
image, cacheType in
completion(image)
}
}
private func download(from imageUrl: String, completion: @escaping (Image?) -> Void) {
ImageDownloader.default.downloadImage(with: URL(string: imageUrl)!, options: [], progressBlock: nil) {
(image, error, url, data) in
completion(image)
}
}
private func saveImageToDisk(with image: Image, key: String) {
ImageCache.default.store(image, forKey: key)
}
}
@kittisak-phetrungnapha
Copy link
Author

Don't forget to install Kingfisher.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment