Created
August 6, 2023 19:02
-
-
Save daltonclaybrook/f414352f184a969da68c1e01ada546c2 to your computer and use it in GitHub Desktop.
A thin wrapper around Kingfisher's image cache
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 | |
final class ImageLoader { | |
private let imageCache: ImageCache | |
init() throws { | |
self.imageCache = try Self.loadImageCache() | |
} | |
/// Store an image in the memory and disk caches | |
func store(image: KFCrossPlatformImage, forKey: String) { | |
imageCache.store(image, forKey: forKey) | |
} | |
/// Asynchronously load an image from memory or disk | |
func loadImage(forKey: String) async -> KFCrossPlatformImage? { | |
await withCheckedContinuation { continuation in | |
imageCache.retrieveImage(forKey: forKey) { result in | |
switch result { | |
case .success(let result): | |
continuation.resume(returning: result.image) | |
case .failure: | |
continuation.resume(returning: nil) | |
} | |
} | |
} | |
} | |
// MARK: - Private helpers | |
private static func loadImageCache() throws -> ImageCache { | |
let memoryStorage = Self.createMemoryStorage() | |
let diskStorage = try Self.createDiskStorage() | |
return ImageCache(memoryStorage: memoryStorage, diskStorage: diskStorage) | |
} | |
/// This memory storage configuration matches the default one used by Kingfisher | |
private static func createMemoryStorage() -> MemoryStorage.Backend<KFCrossPlatformImage> { | |
let totalMemory = ProcessInfo.processInfo.physicalMemory | |
let costLimit = totalMemory / 4 | |
let memoryStorage = MemoryStorage.Backend<KFCrossPlatformImage>(config: | |
.init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit))) | |
return memoryStorage | |
} | |
/// Returns a disk storage configured with no size limit or expiration | |
private static func createDiskStorage() throws -> DiskStorage.Backend<Data> { | |
var config = DiskStorage.Config(name: "com.my.app.image-cache", sizeLimit: .max) | |
config.expiration = .never | |
let diskStorage = try DiskStorage.Backend<Data>(config: config) | |
return diskStorage | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment