CachedAsyncImage

main

CachedAsyncImage is a Swift Package for asynchronously loading images from the web and caching them.
0xWDG/CachedAsyncImage

CachedAsyncImage

CachedAsyncImage is a Swift Package for asynchronously loading images from the web and caching them.

Swift Package Manager License

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)

  1. In Xcode, open your project and navigate to FileSwift PackagesAdd Package Dependency...
  2. Paste the repository URL (https://github.com/0xWDG/CachedAsyncImage) and click Next.
  3. 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

We can get in touch via Twitter/X, Discord, Mastodon, Email, Website.

Description

  • Swift Tools 5.9.0
View More Packages from this Author

Dependencies

  • None
Last updated: Sun Dec 01 2024 14:39:13 GMT-1000 (Hawaii-Aleutian Standard Time)