Skip to content

Commit

Permalink
Expose ImageCache
Browse files Browse the repository at this point in the history
  • Loading branch information
leoz committed Dec 19, 2023
1 parent d263742 commit 6772644
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 12 deletions.
8 changes: 7 additions & 1 deletion Demo/CachedImageDemo/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,19 @@
import SwiftUI
import CachedImage

let images = (0...20).map {
let images = (0...200).map {
"https://picsum.photos/800/600?random=\($0)"
}
let imageURLs = images.map {
URL(string: $0)!
}

struct ContentView: View {
let imageCache = DefaultImageCache(
countLimit: 10000, // 10000 items
totalCostLimit: 1024 * 1024 * 500 // 500 MB
)

var body: some View {
List(imageURLs, id: \.self) { url in
CachedImage(
Expand All @@ -32,6 +37,7 @@ struct ContentView: View {
)
.scaledToFit()
}
.environment(\.imageCache, imageCache)
}
}

Expand Down
4 changes: 2 additions & 2 deletions Sources/CachedImage/EnvironmentValues+ImageCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
import SwiftUI

struct ImageCacheKey: EnvironmentKey {
static let defaultValue: ImageCache = TemporaryImageCache()
static let defaultValue: ImageCache = DefaultImageCache()
}

extension EnvironmentValues {
public extension EnvironmentValues {
var imageCache: ImageCache {
get { self[ImageCacheKey.self] }
set { self[ImageCacheKey.self] = newValue }
Expand Down
32 changes: 23 additions & 9 deletions Sources/CachedImage/ImageCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,33 @@

import SwiftUI

protocol ImageCache {
public protocol ImageCache {
subscript(_ url: URL) -> PlatformImage? { get set }
}

struct TemporaryImageCache: ImageCache {
private let cache: NSCache<NSURL, PlatformImage> = {
let cache = NSCache<NSURL, PlatformImage>()
cache.countLimit = 100 // 100 items
cache.totalCostLimit = 1024 * 1024 * 100 // 100 MB
return cache
}()
public struct DefaultImageCache: ImageCache {
private let cache: NSCache<NSURL, PlatformImage>

subscript(_ key: URL) -> PlatformImage? {
public init(
countLimit: Int,
totalCostLimit: Int
) {
self.cache = {
let cache = NSCache<NSURL, PlatformImage>()
cache.countLimit = countLimit
cache.totalCostLimit = totalCostLimit
return cache
}()
}

public init() {
self.init(
countLimit: 100, // 100 items
totalCostLimit: 1024 * 1024 * 100 // 100 MB
)
}

public subscript(_ key: URL) -> PlatformImage? {
get { cache.object(forKey: key as NSURL) }
set {
newValue == nil ?
Expand Down

0 comments on commit 6772644

Please sign in to comment.