When Swift Concurrency burst onto our screens 5 years in the past, it dangled AsyncImage earlier than our dazzled eyes — see how straightforward it’s now, to obtain and show a picture! It was fast and enjoyable to make use of … in a prototype or pattern app, not in a manufacturing app that wanted picture caching for effectivity and efficiency. Nicely, Xcode 27 fills that hole, bringing AsyncImage caching into your life!
Getting Began
Observe: You want Xcode 27 beta to make use of AsyncImage caching.
Use the Obtain Supplies button on the high or backside of this text to obtain the starter mission.
TheMet is an app that searches The Metropolitan Museum of Artwork, New York for museum objects matching the consumer’s question time period. It’s tailored from the pattern mission in Part III of SwiftUI Apprentice.
TheMet app has a repository TheMetStore and a networking service TheMetService. ContentView shows a color-coded checklist of museum objects. Pale blue objects are within the public area, and you’ll obtain photographs. Pink objects usually are not within the public area, and you should navigate to the museum’s website online to view photographs.
Tapping an object that’s within the public area navigates to ObjectView, which shows details about the article and makes use of AsyncImage as a easy option to fetch a picture of the article. Tapping a pink merchandise navigates to a SafariView of the article’s internet web page on the Metropolitan Museum’s website online.
Caching Pictures
AsyncImage is beneficial for prototyping an app, nevertheless it’s inefficient to fetch a picture each time ObjectView masses. Your app’s efficiency is healthier if it caches photographs.
A few of the Kodeco iOS bootcamps used TheMet to show lists, navigation and networking. An Above-and-Past homework train requested the scholars to switch it to cache the pictures. On the time, this required including a picture information property to Object and changing AsyncImage with a URLSession process to obtain and retailer the picture information. Caching code could possibly be tailored from the EmojiArt mission in Trendy Concurrency. It was a variety of work!
Xcode 27 provides caching to AsyncImage!
AsyncImage caches downloaded picture information following the transport protocol. The system creates the cache with a default URLSessionConfiguration. To alter the cache coverage, specify the change in URLRequest, and cross it to init(request:scale:transaction:content material:). To customise the obtain course of in a selected view hierarchy, use asyncImageURLSession(_:) to specify a URLSession. AsyncImage makes use of this session to carry out information duties when downloading the picture information.
On this tutorial, I interpret “default URLSessionConfiguration” to imply that AsyncImage makes use of URLSession.shared as its default URLSession. As you’ll see, when AsyncImage is utilizing the default session, the scale of URLCache.shared will increase at any time when AsyncImage downloads a brand new picture. You’ll additionally learn to change the cache coverage and methods to specify a customized URLSession.
Caching in Motion
The quickest option to see AsyncImage caching in motion is to check what it does in Xcode 26 with what occurs in Xcode 27. If you happen to’re studying this after Xcode 27’s launch, and don’t have Xcode 26 anymore, skip to the following part, the place you’ll set the cachePolicy of a URLRequest.
If you happen to’re studying this whereas Xcode 27 continues to be in beta, open TheMet in Xcode 26, then open ContentView.swift and cargo its preview. When the rhino checklist masses, faucet one of many pale blue objects to load its ObjectView.
After the picture masses, navigate again to the checklist. Now, flip off wifi in your Mac, then faucet the identical blue merchandise — no picture!
Xcode 26’s AsyncImage doesn’t have caching, so ObjectView tries — and fails — to obtain the picture once more.
Stop Xcode 26, flip wifi again on, then open TheMet in Xcode 27. Within the ContentView preview canvas, faucet a unique pale blue merchandise, anticipate the picture to load in ObjectView, then faucet again to the checklist.
Flip off wifi, then faucet the identical merchandise — AsyncImage retrieves the picture from its cache!
Setting Cache Coverage
In ContentView, pin its preview:
Now, open ObjectView.swift and find the AsyncImage(url:) name.
AsyncImage makes use of the shared URLSession occasion, which makes use of the default URLSessionConfiguration. The default cachePolicy is useProtocolCachePolicy, whose key conduct is:
if the cached response doesn’t point out that it should be revalidated each time, and if the cached response is just not stale (previous its expiration date), the URL loading system returns the cached response.
Xcode documentation supplies this helpful circulate chart:
The obtainable cache insurance policies are enumerated in NSURLRequest.CachePolicy. They mean you can ignore native and/or distant cache information or use possibly-expired cache information:
-
reloadIgnoringLocalCacheData: The URL load ought to be loaded solely from the originating supply. -
reloadIgnoringLocalAndRemoteCacheData: Ignore native cache information, and instruct proxies and different intermediates to ignore their caches as far as the protocol permits. -
returnCacheDataElseLoad: Use present cache information, no matter age or expiration date, loading from originating supply provided that there isn’t a cached information. -
returnCacheDataDontLoad: Use present cache information, no matter age or expiration date, and fail if no cached information is on the market. -
reloadRevalidatingCacheData: Use cache information if the origin supply can validate it; in any other case, load from the origin.
You’ll be able to change cachePolicy in a URLRequest. Simply above the AsyncImage(url:) name is a TODO:
TODO: Create request to set its cachePolicy
Substitute this with the next code:
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
Then, within the subsequent TODO, exchange the url initializer:
AsyncImage(url: url) { picture in
with the URLRequest initializer:
AsyncImage(request: request) { picture in
This initializer is new in Xcode 27.
Now, within the ContentView preview, undergo the identical routine: load a picture in ObjectView, return to the checklist, flip off wifi, then load the identical ObjectView. Since you’re now ignoring native cache information, there’s no picture.
Change cachePolicy to useProtocolCachePolicy and see for your self that AsyncImage retrieves the cached picture.
Bear in mind to show wifi again on.
Displaying Cache Dimension
You will get or set on-disk and in-memory cache properties:
- currentDiskUsage
- diskCapacity
- currentMemoryUsage
- memoryCapacity
Scroll down in ObjectView to the final Textual content view. Just under that is one other TODO:
Show present disk utilization
Substitute the TODO with the next code:
Textual content("Shared Cache (KB): " +
String((URLCache.shared.currentDiskUsage / 1024)))
Sure! URLCache has a category variable shared — a lot shorter than URLSession.shared.configuration.urlCache!
Now, while you faucet an inventory merchandise, you see how a lot is within the shared cache:
Your quantity is perhaps totally different, relying on what number of instances you’ve loaded ObjectView.
