Impressia/Vernissage/Services/CacheImageService.swift

49 lines
1.3 KiB
Swift
Raw Normal View History

2023-01-18 18:41:42 +01:00
//
// https://mczachurski.dev
// Copyright © 2023 Marcin Czachurski and the repository contributors.
// Licensed under the MIT License.
//
import Foundation
import SwiftUI
public class CacheImageService {
public static let shared = CacheImageService()
private init() { }
2023-01-26 20:35:24 +01:00
private var memoryCacheData = MemoryCache<URL, Image>(entryLifetime: 600)
2023-01-18 18:41:42 +01:00
2023-01-24 20:38:21 +01:00
func addImage(for url: URL, data: Data) {
2023-01-18 18:41:42 +01:00
if let uiImage = UIImage(data: data) {
2023-01-26 20:35:24 +01:00
self.memoryCacheData[url] = Image(uiImage: uiImage)
2023-01-18 18:41:42 +01:00
}
}
2023-01-24 20:38:21 +01:00
func addImage(for url: URL, image: Image) {
2023-01-26 20:35:24 +01:00
self.memoryCacheData[url] = image
2023-01-18 18:41:42 +01:00
}
2023-01-24 20:38:21 +01:00
func downloadImage(url: URL?) async {
guard let url else {
2023-01-18 18:41:42 +01:00
return
}
2023-01-26 20:35:24 +01:00
if memoryCacheData[url] != nil {
2023-01-18 18:41:42 +01:00
return
}
do {
let imageData = try await RemoteFileService.shared.fetchData(url: url)
if let imageData {
2023-01-24 20:38:21 +01:00
CacheImageService.shared.addImage(for: url, data: imageData)
2023-01-18 18:41:42 +01:00
}
} catch {
ErrorService.shared.handle(error, message: "Downloading image into cache failed.")
}
}
2023-01-24 20:38:21 +01:00
func getImage(for url: URL) -> Image? {
2023-01-26 20:35:24 +01:00
return self.memoryCacheData[url]
2023-01-18 18:41:42 +01:00
}
}