Jun 07, 2021

Rendering Remote Images with AsyncImage

With WWDC21 being kicked off officially, all technologies have received major upgrades, including SwiftUI. One of the bigger changes, a new view has been added to solve a complex problem SwiftUI developers faced until now: Loading remote images.

The new AsyncImage view allows to load and display any arbitrary image from a given URL, using the shared URLSession.

The most simple version loads and renders a remote image

AsyncImage(url: URL(string: "https://example.com/screenshot.png"))

While this is great already, not only can you modify how the image is displayed using the content parameter, you can also customize the placeholder value that sticks around until the image is fully loaded.

AsyncImage(url: URL(string: "https://example.com/tile.png")) { image in
    image.resizable(resizingMode: .tile)
} placeholder: {
    Color.green
}

If you need even more control, you can customize what should be displayed through every phase of the fetching lifecycle (empty, success, failure)

AsyncImage(url: URL(string: "https://example.com/icon.png")) { phase in
    if let image = phase.image {
        image
    } else if phase.error != nil {
        Color.red.frame(width: 128, height: 128)
    } else {
        Color.blue.frame(width: 128, height: 128)
    }
}

Adding a view that allows rendering remote images this easily increases the development speed incredibly, making it much quicker to prototype applications, without having to think about the tedious task of fetching image data, and displaying it, or using a library that might be deprecated in the future.