ImageCache.swift

1.0 KB · raw

1import AppKit23class ImageCache {4  static let shared = ImageCache()5  private let cache = NSCache<NSString, NSImage>()6  private let session: URLSession78  init(session: URLSession = .shared) {9    self.session = session10  }1112  func image(for url: URL) -> NSImage? {13    return cache.object(forKey: url.absoluteString as NSString)14  }1516  func insertImage(_ image: NSImage, for url: URL) {17    cache.setObject(image, forKey: url.absoluteString as NSString)18  }1920  func fetchImage(url: URL) async throws -> NSImage {21    if let cached = image(for: url) {22      return cached23    }2425    let (data, response) = try await session.data(from: url)26    guard let response = response as? HTTPURLResponse,27      (200...299).contains(response.statusCode)28    else {29      throw WallhavenError.apiError("Image download failed")30    }31    guard let image = NSImage(data: data) else {32      throw WallhavenError.decodingError(NSError(domain: "ImageCache", code: -1, userInfo: nil))33    }3435    insertImage(image, for: url)36    return image37  }38}