Mastering Swift's Development Blog

Follow Us On Twitter
  • Jon Hoffman

Caching AsyncImage SwiftUI

Updated: Aug 18


A while back I was creating a list view where each element in the list displayed an image which was download from a web API and I use AsyncImage which is provided with SwiftUI to download and display the image. While building this app, I noticed that while scrolling through the list view, the images were downloaded each time an element was displayed. Even if the image was previously downloaded, AsyncImage would download it again. I thought that this was a waste of data and started looking for a way to cache the images. During this search I came across the CachedAsyncImage package: https://github.com/lorenzofiamingo/swiftui-cached-async-image


CachedAsyncImage is exactly what AsyncImage is except with caching capabilities. The best thing about this package is it provides a drop-in replacement for AsyncImage where no other code changes are necessary therefore in your code wherever you are using the following code:

AsyncImage(url:  urlToImage)

All you need to do is to change it to this:

CachedAsyncImage(url: urlToImage)

And caching capabilities will be added. I use this package anytime I have a list or a scroll view that requires an image and we use it throughout the Open Source Mastering Swift Cocktail app. As an example, in the CocktailColumn view I use CachedAsyncImage like this:

CachedAsyncImage(url: URL(string: strDrinkThumb)) { phase in
    switch phase {
         case .empty:
              ProgressView()
         case .success(let image):
              image.resizable()
                    .scaledToFit()
         case .failure:
              Image(systemName: "photo")
         @unknown default:
              EmptyView()
         }
  }
  .frame(width: 150, height: 150)
  .padding(.bottom, 10)      

Notice that the CachedAsyncImage is used exactly like the AsyncImage with the AsyncImagePhases to change the image while it is being loaded or if there is a failure in loading.


There are installations instructions of CachedAsyncImage on the Github page for the project here: https://github.com/lorenzofiamingo/swiftui-cached-async-image


masteringSwift.jpeg

Mastering Swift 5.3

The sixth edition of this bestselling book, updated to cover through version 5.3 of the Swift programming language

Amazon

Packt

pop.jpeg

Protocol Oriented Programming

Embrace the Protocol-Oriented design paradigm, for better code maintainability and increased performance, with Swift.

Amazon

Packt