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-24 20:38:21 +01:00
private var memoryChartData = 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-24 20:38:21 +01:00
self.memoryChartData[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) {
self.memoryChartData[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-24 20:38:21 +01:00
if memoryChartData[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? {
return self.memoryChartData[url]
2023-01-18 18:41:42 +01:00
}
}