From 0bbfab75dd90a9036ec282eb9a9c2debe75712dc Mon Sep 17 00:00:00 2001 From: Alex Grebenyuk Date: Sun, 1 Nov 2026 17:44:09 -0500 Subject: [PATCH] Add an article on replacing AsyncImage with LazyImage Covers the swap for each AsyncImage initializer, where the behavior differs (a missing URL is an error, the error is typed, disappearing cancels the load), the environment pipeline as the counterpart of asyncImageURLSession(_:), and a phase helper for code that takes an AsyncImagePhase. Every sample is compiled by the documentation snippets. --- .scripts/generate-llms.py | 1 + .../Essentials/replacing-async-image.md | 148 +++++++++++++++++ Documentation/Nuke.docc/Essentials/swiftui.md | 2 +- Documentation/Nuke.docc/Nuke.md | 1 + .../ReplacingAsyncImageSnippets.swift | 152 ++++++++++++++++++ 5 files changed, 303 insertions(+), 1 deletion(-) create mode 100644 Documentation/Nuke.docc/Essentials/replacing-async-image.md create mode 100644 Tests/DocumentationSnippets/Snippets/ReplacingAsyncImageSnippets.swift diff --git a/.scripts/generate-llms.py b/.scripts/generate-llms.py index 753fea3c4..6dde94e4c 100644 --- a/.scripts/generate-llms.py +++ b/.scripts/generate-llms.py @@ -44,6 +44,7 @@ ARTICLE_ORDER = [ "Essentials/getting-started.md", "Essentials/swiftui.md", + "Essentials/replacing-async-image.md", "Essentials/uikit.md", "AnimatedImages.md", "Essentials/troubleshooting.md", diff --git a/Documentation/Nuke.docc/Essentials/replacing-async-image.md b/Documentation/Nuke.docc/Essentials/replacing-async-image.md new file mode 100644 index 000000000..23f7d2980 --- /dev/null +++ b/Documentation/Nuke.docc/Essentials/replacing-async-image.md @@ -0,0 +1,148 @@ +# Replacing AsyncImage + +Move from SwiftUI's `AsyncImage` to `LazyImage`, and learn what changes. + +## Overview + +`LazyImage` is shaped like `AsyncImage`: it takes a URL or a request, and a closure that builds the view for each state. The difference is where the image comes from. `AsyncImage` loads it with a `URLSession`. `LazyImage` loads it with an ``ImagePipeline``, so the image is cached in memory, a download that is already running is shared, the decoding happens off the main thread, and the request is canceled when the view goes away. + +Most of the move is mechanical. Add `import NukeUI`, rename the view, and replace the `switch` on the phase with a check of the state. + +## The Common Case + +`AsyncImage` passes the closure a phase. `LazyImage` passes it the state, which has the same three outcomes as properties: `image` for `.success`, `error` for `.failure`, and neither for `.empty`. + +```swift +// AsyncImage +AsyncImage(url: url) { phase in + switch phase { + case .success(let image): + image.resizable().scaledToFill() + case .failure: + Image(systemName: "photo") + case .empty: + ProgressView() + @unknown default: + EmptyView() + } +} + +// LazyImage +LazyImage(url: url) { state in + if let image = state.image { + image.resizable().scaledToFill() + } else if state.error != nil { + Image(systemName: "photo") + } else { + ProgressView() + } +} +``` + +The same goes for the form with a separate placeholder. There is no `placeholder` closure, so the `else` branch is the placeholder. + +```swift +// AsyncImage +AsyncImage(url: url) { image in + image.resizable() +} placeholder: { + ProgressView() +} + +// LazyImage +LazyImage(url: url) { state in + if let image = state.image { + image.resizable() + } else { + ProgressView() + } +} +``` + +## Initializers + +| AsyncImage | LazyImage | +|---|---| +| `AsyncImage(url:)` | `LazyImage(url:)` | +| `AsyncImage(url:scale:)` | Set `scale` on an ``ImageRequest``, as shown below | +| `AsyncImage(url:scale:content:placeholder:)` | `LazyImage(url:content:)`, with the placeholder in the `else` branch | +| `AsyncImage(url:scale:transaction:content:)` | `LazyImage(url:transaction:content:)` | +| `AsyncImage(request:)` and the other `request:` forms, on iOS 27 | `LazyImage(request:)` with ``ImageRequest/init(urlRequest:processors:priority:options:)``, from iOS 16 | +| `.asyncImageURLSession(_:)` | `.imagePipeline(_:)`, as shown below | +| `phase.image` | `state.image` | +| `phase.error` | `state.error` | + +`AsyncImage` takes a `scale` because `Image` needs to know how many pixels make a point. `LazyImage` takes it from the request, and it is `1` by default, like the `scale` of `AsyncImage`. + +```swift +var request = ImageRequest(url: url) +request.scale = 3 + +LazyImage(request: request) { state in + if let image = state.image { + image + } +} +``` + +To load with the headers, the cache policy, or the timeout of a `URLRequest`, pass it to the request. + +```swift +LazyImage(request: ImageRequest(urlRequest: urlRequest)) { state in + if let image = state.image { + image + } +} +``` + +## Setting the Session + +`asyncImageURLSession(_:)` sets the session that every `AsyncImage` below it loads with. `imagePipeline(_:)` does the same for `LazyImage`. Nuke builds the session itself, from the configuration of a ``DataLoader``, so that's where you put the headers, the timeouts, and the cache. + +```swift +let configuration = DataLoader.defaultConfiguration +configuration.httpAdditionalHeaders = ["Authorization": "Bearer \(token)"] + +let pipeline = ImagePipeline { + $0.dataLoader = DataLoader(configuration: configuration) +} + +ContentView() + .imagePipeline(pipeline) +``` + +A pipeline set on a single view with `pipeline(_:)` takes precedence over the one in the environment. Without either, `LazyImage` loads with ``ImagePipeline/shared``. See for the ways to customize how the data is loaded, including authentication challenges. + +## Where the Behavior Differs + +A view that is moved over compiles, but a few things work differently. + +- **A missing URL is an error.** `LazyImage(url: nil)` doesn't stay in its loading state. It fails with ``ImagePipeline/Error/imageRequestMissing``, so `state.error` isn't `nil`. If a missing URL means that there is no image to show, check for it before you create the view. +- **The error has a type.** `state.error` is an ``ImagePipeline/Error``, and `AsyncImagePhase.failure` carries an `any Error`. Use the `dataLoadingFailed(error:)` case to get the error that `URLSession` reported. +- **Disappearing cancels the load.** The request is canceled when the view disappears, and it starts again when the view comes back. To change that, use `onDisappear(_:)`. + +## Code That Takes a Phase + +If your views take an `AsyncImagePhase`, for example a shared helper that draws every state in the same way, you don't have to rewrite them. Make a phase from the state. + +```swift +extension LazyImageState { + var phase: AsyncImagePhase { + if let image { + .success(image) + } else if let error { + .failure(error) + } else { + .empty + } + } +} + +LazyImage(url: url) { state in + AvatarContent(phase: state.phase) +} +``` + +## What You Get in Return + +The phase has no room for most of what the pipeline knows, which is why the closure gets the state. Once you're on `LazyImage`, you can read `progress` and `isLoading`, set the `processors` and the `priority`, and play animated images. See for the rest of `LazyImage`, to resize an image to the size it is displayed at, and for the settings that matter in a list. diff --git a/Documentation/Nuke.docc/Essentials/swiftui.md b/Documentation/Nuke.docc/Essentials/swiftui.md index 55ab5e5ae..2515c46ff 100644 --- a/Documentation/Nuke.docc/Essentials/swiftui.md +++ b/Documentation/Nuke.docc/Essentials/swiftui.md @@ -47,7 +47,7 @@ LazyImage(url: url) { state in .clipped() ``` -> Note: Unlike `AsyncImage`, `LazyImage` doesn't pass a phase enum to the closure – it passes the state itself, so you can read the download progress or the underlying ``ImageResponse`` while the view is on screen. +> Note: Unlike `AsyncImage`, `LazyImage` doesn't pass a phase enum to the closure – it passes the state itself, so you can read the download progress or the underlying ``ImageResponse`` while the view is on screen. See if you're moving from `AsyncImage`. ## Transitions diff --git a/Documentation/Nuke.docc/Nuke.md b/Documentation/Nuke.docc/Nuke.md index b82d6ff50..906cb6c4a 100644 --- a/Documentation/Nuke.docc/Nuke.md +++ b/Documentation/Nuke.docc/Nuke.md @@ -30,6 +30,7 @@ To install Nuke, use Swift Package Manager. - - +- - - - diff --git a/Tests/DocumentationSnippets/Snippets/ReplacingAsyncImageSnippets.swift b/Tests/DocumentationSnippets/Snippets/ReplacingAsyncImageSnippets.swift new file mode 100644 index 000000000..94fa3951e --- /dev/null +++ b/Tests/DocumentationSnippets/Snippets/ReplacingAsyncImageSnippets.swift @@ -0,0 +1,152 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2026 Alexander Grebenyuk (github.com/kean). + +// Snippets from `Documentation/Nuke.docc/Essentials/replacing-async-image.md`. +// +// This target exists only to make the hand-written samples in the articles +// compile. If a snippet here stops building, the article is out of date. + +import SwiftUI +import NukeUI + +// MARK: - The Common Case + +private struct CommonCaseViews: View { + let url: URL + + var body: some View { + // AsyncImage + AsyncImage(url: url) { phase in + switch phase { + case .success(let image): + image.resizable().scaledToFill() + case .failure: + Image(systemName: "photo") + case .empty: + ProgressView() + @unknown default: + EmptyView() + } + } + + // LazyImage + LazyImage(url: url) { state in + if let image = state.image { + image.resizable().scaledToFill() + } else if state.error != nil { + Image(systemName: "photo") + } else { + ProgressView() + } + } + } +} + +private struct PlaceholderViews: View { + let url: URL + + var body: some View { + // AsyncImage + AsyncImage(url: url) { image in + image.resizable() + } placeholder: { + ProgressView() + } + + // LazyImage + LazyImage(url: url) { state in + if let image = state.image { + image.resizable() + } else { + ProgressView() + } + } + } +} + +// MARK: - Initializers + +private struct ScaleView: View { + let url: URL + + var body: some View { + let request = { + var request = ImageRequest(url: url) + request.scale = 3 + return request + }() + + LazyImage(request: request) { state in + if let image = state.image { + image + } + } + } +} + +private struct URLRequestView: View { + let urlRequest: URLRequest + + var body: some View { + LazyImage(request: ImageRequest(urlRequest: urlRequest)) { state in + if let image = state.image { + image + } + } + } +} + +// MARK: - Setting the Session + +private struct SessionView: View { + let token: String + + var body: some View { + let configuration = DataLoader.defaultConfiguration + configuration.httpAdditionalHeaders = ["Authorization": "Bearer \(token)"] + + let pipeline = ImagePipeline { + $0.dataLoader = DataLoader(configuration: configuration) + } + + return ContentView() + .imagePipeline(pipeline) + } +} + +private struct ContentView: View { + var body: some View { EmptyView() } +} + +// MARK: - Code That Takes a Phase + +extension LazyImageState { + var phase: AsyncImagePhase { + if let image { + .success(image) + } else if let error { + .failure(error) + } else { + .empty + } + } +} + +private struct PhaseView: View { + let url: URL + + var body: some View { + LazyImage(url: url) { state in + AvatarContent(phase: state.phase) + } + } +} + +private struct AvatarContent: View { + let phase: AsyncImagePhase + + var body: some View { + phase.image ?? Image(systemName: "person") + } +}