Impressia/Vernissage/Services/CacheAvatarService.swift

46 lines
1.2 KiB
Swift
Raw Normal View History

2023-01-05 21:08:19 +01:00
//
// https://mczachurski.dev
// Copyright © 2023 Marcin Czachurski and the repository contributors.
// Licensed under the MIT License.
//
import Foundation
import SwiftUI
public class CacheAvatarService {
public static let shared = CacheAvatarService()
private init() { }
2023-01-06 18:16:08 +01:00
private var memoryChartData = MemoryCache<String, UIImage>(entryLifetime: 5 * 60)
2023-01-06 13:05:21 +01:00
2023-01-05 21:08:19 +01:00
func addImage(for id: String, data: Data) {
if let uiImage = UIImage(data: data) {
2023-01-06 18:16:08 +01:00
self.memoryChartData[id] = uiImage
2023-01-05 21:08:19 +01:00
}
}
2023-01-06 13:05:21 +01:00
func downloadImage(for accountId: String?, avatarUrl: URL?) async {
guard let accountId, let avatarUrl else {
return
}
2023-01-06 18:16:08 +01:00
if memoryChartData[accountId] != nil {
return
}
2023-01-06 13:05:21 +01:00
do {
let avatarData = try await RemoteFileService.shared.fetchData(url: avatarUrl)
if let avatarData {
CacheAvatarService.shared.addImage(for: accountId, data: avatarData)
}
} catch {
print("Error \(error.localizedDescription)")
}
}
2023-01-05 21:08:19 +01:00
func getImage(for id: String) -> UIImage? {
2023-01-06 18:16:08 +01:00
return self.memoryChartData[id]
2023-01-05 21:08:19 +01:00
}
}