summaryrefslogtreecommitdiff
path: root/Sora/Data/ImageCacheManager.swift
blob: 414ad4c55a65319668eabfd3e7d34367d55329b9 (plain) (blame)
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
import Combine
import SwiftUI

final class ImageCacheManager {
  // MARK: - Shared Instance
  static let shared = ImageCacheManager()

  // MARK: - Private Properties
  private let cache = URLCache(
    memoryCapacity: 100 * 1_024 * 1_024,  // 100 MB
    diskCapacity: 500 * 1_024 * 1_024,  // 500 MB
    directory: FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?
      .appendingPathComponent("SoraImageCache", isDirectory: true)
  )
  private var cancellables = Set<AnyCancellable>()

  // MARK: - Initialization
  private init() {
    URLCache.shared = cache
  }

  // MARK: - Public Methods
  func preloadImages(_ urls: [URL]) {
    urls.forEach { url in
      URLSession.shared.dataTaskPublisher(for: url)
        .map { CachedURLResponse(response: $0.response, data: $0.data) }
        .sink(
          receiveCompletion: { _ in () },
          receiveValue: { [cache] in cache.storeCachedResponse($0, for: URLRequest(url: url)) }
        )
        .store(in: &cancellables)
    }
  }
}