Better image caching

This commit is contained in:
Vicnet
2023-09-17 16:37:08 +02:00
parent 3504ce2a25
commit 9088301b15
3 changed files with 37 additions and 28 deletions

View File

@@ -77,7 +77,7 @@ import UIKit
/// - needsUpdate: Determines wether the image should be loaded directly from the server, or if it should be loaded from cache/store first.
/// - Returns: The image if found locally or on the server, otherwise nil.
func loadImage(recipeId: Int, full: Bool, needsUpdate: Bool = false) async -> UIImage? {
print("loadImage(recipeId: \(recipeId), full: \(full))")
print("loadImage(recipeId: \(recipeId), full: \(full), needsUpdate: \(needsUpdate)")
// If the image needs an update, request it from the server and overwrite the stored image
if needsUpdate {
if let data = await imageDataFromServer(recipeId: recipeId, full: full) {
@@ -88,17 +88,23 @@ import UIKit
}
}
// Try to load image from cache
print("Attempting to load image from local storage ...")
if let image = imageFromCache(recipeId: recipeId, full: full) {
return image
print("Attempting to load image from cache ...")
if imageCache[recipeId] != nil {
print("Image found in cache.")
return imageFromCache(recipeId: recipeId, full: full)
}
// Try to load from store
print("Attempting to load image from server ...")
print("Attempting to load image from local storage ...")
if let image = await imageFromStore(recipeId: recipeId, full: full) {
print("Image found in local storage.")
imageToCache(image: image, recipeId: recipeId, full: full)
return image
}
// Try to load from the server. Store if successfull.
print("Attempting to load image from server ...")
if let data = await imageDataFromServer(recipeId: recipeId, full: full) {
print("Image data received.")
imageCache[recipeId] = RecipeImage() // Create empty RecipeImage for each recipe even if no image found, so that further server requests are only sent if explicitly requested.
guard let image = UIImage(data: data) else { return nil }
await dataStore.save(data: data.base64EncodedString(), toPath: localImagePath(recipeId, full))
imageToCache(image: image, recipeId: recipeId, full: full)