Image generated with AI

Member-only story

Async Image in SwiftUI

Nicola De Filippo
2 min readSep 2, 2024

If your app needs to display images that are hosted on a server, this post is for you. It’s a common scenario where images aren’t downloaded or are not present in the application’s assets. Another common issue is displaying a progress indicator until the image is fully displayed. AsyncImage is the solution to all these requests.

IIn this post, I use as a starting point the code discussed in a previous post (https://nicoladefilippo.com/pull-refresh-in-swiftui/), where we loaded a list of beer names. Now, we will also add images. Here is the code:

struct Beer: Codable, Identifiable {
var id: Int
var name: String
}

struct ContentView: View {
@State var beers: [Beer] = []
@State var page = 0
var body: some View {
NavigationStack {
List(beers) { beer in
Text(beer.name)
}.refreshable {
await getBeers()
}
}.onAppear {
Task {
await getBeers()
}
}
}

func getBeers() async {
do {
page += 1
let url = URL(string: "https://api.punkapi.com/v2/beers?page=\(page)&per_page=30")!
let (data, _) = try await URLSession.shared.data(from: url)
let beersDownloaded = try JSONDecoder().decode([Beer].self, from: data)
beers = beersDownloaded + beers
} catch {

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Nicola De Filippo
Nicola De Filippo

Written by Nicola De Filippo

Software Engineer and Entrepreneur

No responses yet

Write a response