Impressia/Vernissage/Services/CacheImageService.swift

45 lines
1.1 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-28 21:09:31 +01:00
func download(url: URL?) async {
2023-01-24 20:38:21 +01:00
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-28 21:09:31 +01:00
self.add(data: imageData, for: url)
2023-01-18 18:41:42 +01:00
}
} catch {
ErrorService.shared.handle(error, message: "Downloading image into cache failed.")
}
}
2023-01-28 21:09:31 +01:00
func get(for url: URL) -> Image? {
2023-01-26 20:35:24 +01:00
return self.memoryCacheData[url]
2023-01-18 18:41:42 +01:00
}
2023-01-28 21:09:31 +01:00
private func add(data: Data, for url: URL) {
if let uiImage = UIImage(data: data) {
self.memoryCacheData[url] = Image(uiImage: uiImage)
}
}
2023-01-18 18:41:42 +01:00
}