ImageCache.swift

867 B · raw

1import AppKit23class ImageCache {4    static let shared = ImageCache()5    private let cache = NSCache<NSString, NSImage>()6    7    private init() {}8    9    func image(for url: URL) -> NSImage? {10        return cache.object(forKey: url.absoluteString as NSString)11    }12    13    func insertImage(_ image: NSImage, for url: URL) {14        cache.setObject(image, forKey: url.absoluteString as NSString)15    }16    17    func fetchImage(url: URL) async throws -> NSImage {18        if let cached = image(for: url) {19            return cached20        }21        22        let (data, _) = try await URLSession.shared.data(from: url)23        guard let image = NSImage(data: data) else {24            throw WallhavenError.decodingError(NSError(domain: "ImageCache", code: -1, userInfo: nil))25        }26        27        insertImage(image, for: url)28        return image29    }30}