Last active
October 29, 2018 18:45
-
-
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.
This file contains hidden or 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
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't forget to install Kingfisher.