0xWDG/CachedAsyncImage
CachedAsyncImage is a Swift Package for asynchronously loading images from the web and caching them.
Requirements
- Swift 5.9+ (Xcode 15+)
- iOS 13+, macOS 10.15+
Installation (Pakage.swift)
dependencies: [
.package(url: "https://github.com/0xWDG/CachedAsyncImage.git", branch: "main"),
],
targets: [
.target(name: "MyTarget", dependencies: [
.product(name: "CachedAsyncImage", package: "CachedAsyncImage"),
]),
]Installation (Xcode)
- 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.
Usage
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).
Contact
π¦ @0xWDG π mastodon.social/@0xWDG π¦ @0xWDG π§΅ @0xWDG π wesleydegroot.nl π€ Discord
Interested learning more about Swift? Check out my blog.
Package Metadata
Repository: 0xWDG/CachedAsyncImage
Homepage: https://0xwdg.github.io/CachedAsyncImage/
Stars: 14
Forks: 0
Open issues: 0
Default branch: main
Primary language: swift
License: MIT
Topics: 0xwdg, async, asyncimage, cached, cachedasyncimage, hacktoberfest, images, spm, swiftui
README: README.md