-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added complete image caching solution to the demo app
- Loading branch information
Showing
7 changed files
with
345 additions
and
93 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
// | ||
// ImageCache.swift | ||
// | ||
// Created by Hovik Melikyan on 28.06.24. | ||
// | ||
|
||
import SwiftUI | ||
import AsyncMux | ||
|
||
|
||
private let capacity = 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) | ||
} | ||
|
||
|
||
@AsyncMedia | ||
private static func requestRemote(_ url: URL) async throws -> Image { | ||
let localURL = try await AsyncMedia.shared.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: capacity) | ||
|
||
private static let semaphore = DispatchSemaphore(value: 1) | ||
} |
Oops, something went wrong.