-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathImageCache.swift
64 lines (46 loc) · 1.54 KB
/
ImageCache.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// ImageCache.swift
//
// Created by Hovik Melikyan on 28.06.24.
//
import SwiftUI
import AsyncMux
private let CacheCapacity = 20
final class ImageCache {
static func request(_ url: URL) async throws -> Image {
if let image = loadFromMemory(url) {
return image
}
let image = try await Self.requestRemote(url)
storeToMemory(url: url, image: image)
return image
}
static func loadFromMemory(_ url: URL) -> Image? {
semaphore.wait()
defer { semaphore.signal() }
return memCache.touch(key: url)
}
static func clear() {
semaphore.wait()
defer { semaphore.signal() }
memCache.removeAll()
}
// MARK: - Private part
private static func storeToMemory(url: URL, image: Image) {
semaphore.wait()
defer { semaphore.signal() }
memCache.set(image, forKey: url)
}
@AsyncMediaActor
private static func requestRemote(_ url: URL) async throws -> Image {
let localURL = try await AsyncMedia.request(url: url)
guard let uiImage = UIImage(contentsOfFile: localURL.path) else {
try? FileManager.default.removeItem(at: localURL) // reove the damaged file
throw AppError(code: "cached_file_damaged", message: "Internal: cached file damaged")
}
return Image(uiImage: uiImage)
}
nonisolated(unsafe)
private static var memCache = LRUCache<URL, Image>(capacity: CacheCapacity)
private static let semaphore = DispatchSemaphore(value: 1)
}