From 4747cf0ce0d65ae73e2ead79448ac6a7ddaf7aaf Mon Sep 17 00:00:00 2001 From: Juan Arzola Date: Sun, 23 Mar 2025 16:40:26 -0700 Subject: [PATCH] Make URLSessionConfiguration configurable by the client --- README.md | 6 ++++++ .../CachedAsyncImage/CachedAsyncImage.swift | 20 ++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index bc25925..22b6f2e 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,12 @@ extension URLCache { Remember when setting the cache the response (in this case our image) must be no larger than about 5% of the disk cache (See [this discussion](https://developer.apple.com/documentation/foundation/nsurlsessiondatadelegate/1411612-urlsession#discussion)). +You can also modify the `URLSessionConfiguration` used by `CachedAsyncImage` via `URLSessionConfiguration.cachedAsyncImage`: + +```swift +URLSessionConfiguration.cachedAsyncImage.protocolClasses = [MyContentProtocol.self] +``` + ## Installation 1. In Xcode, open your project and navigate to **File** → **Swift Packages** → **Add Package Dependency...** diff --git a/Sources/CachedAsyncImage/CachedAsyncImage.swift b/Sources/CachedAsyncImage/CachedAsyncImage.swift index 4ba71d7..0962f9b 100644 --- a/Sources/CachedAsyncImage/CachedAsyncImage.swift +++ b/Sources/CachedAsyncImage/CachedAsyncImage.swift @@ -294,7 +294,7 @@ public struct CachedAsyncImage: View where Content: View { /// - content: A closure that takes the load phase as an input, and /// returns the view to display for the specified phase. public init(urlRequest: URLRequest?, urlCache: URLCache = .shared, scale: CGFloat = 1, transaction: Transaction = Transaction(), @ViewBuilder content: @escaping (AsyncImagePhase) -> Content) { - let configuration = URLSessionConfiguration.default + let configuration = URLSessionConfiguration.cachedAsyncImage configuration.urlCache = urlCache self.urlRequest = urlRequest self.urlSession = URLSession(configuration: configuration) @@ -404,3 +404,21 @@ private extension URLSession { return (data, response, controller.metrics!) } } + +// MARK: - URLSessionConfiguration + +@MainActor +private var urlSessionConfig = URLSessionConfiguration.default +extension URLSessionConfiguration { + + /// Default configuration used by `CachedAsyncImage`. + @MainActor + public static var cachedAsyncImage: URLSessionConfiguration { + get { + urlSessionConfig + } + set { + urlSessionConfig = newValue + } + } +}