CachedAsyncImage is a Swift Package for asynchronously loading images from the web and caching them.
- Swift 5.9+ (Xcode 15+)
- iOS 13+, macOS 10.15+
dependencies: [
.package(url: "https://github.com/0xWDG/CachedAsyncImage.git", branch: "main"),
],
targets: [
.target(name: "MyTarget", dependencies: [
.product(name: "CachedAsyncImage", package: "CachedAsyncImage"),
]),
]
- In Xcode, open your project and navigate to File → Swift Packages → Add Package Dependency...
- Paste the repository URL (
https://github.com/0xWDG/CachedAsyncImage
) and click Next. - Click Finish.
CachedAsyncImage
has the exact same API and behavior as AsyncImage
, so you just have to change this:
AsyncImage(url: logoURL)
to this:
CachedAsyncImage(url: logoURL)
example:
import SwiftUI
import CachedAsyncImage
struct ContentView: View {
var body: some View {
VStack {
CachedAsyncImage(
url: URL(
string: "https://wesleydegroot.nl/assets/avatar/avatar.webp"
)
) { image in
image
.resizable()
.frame(width: 250, height: 250)
} placeholder: {
ProgressView()
}
}
.padding()
}
}
In addition to AsyncImage
initializers, you have the possibilities to specify the cache you want to use (by default URLCache.shared
is used), and to use URLRequest
instead of URL
:
CachedAsyncImage(urlRequest: logoURLRequest, urlCache: .imageCache)
// URLCache+imageCache.swift
extension URLCache {
static let imageCache = URLCache(memoryCapacity: 512_000_000, diskCapacity: 10_000_000_000)
}
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).
We can get in touch via Twitter/X, Discord, Mastodon, Email, Website.