Lukas Pistrol Logo

Lukas Pistrol

SwiftUI: AsyncImage

Before iOS 15 it was a real pain to load images from a server and display them in a SwiftUI view. But now Apple gives you an easy way to do exactly that with AsyncImage without any Network Request code necessary. Let's dive right in:

First of all create a new SwiftUI project in Xcode. Then open your ContentView struct and replace the Text("Hello, World!") with this:

AsyncImage(url: URL(string: "")) { image in
  image
    .resizable()
    .aspectRatio(contentMode: .fit)
} placeholder: {
  ProgressView()
}
.frame(width: 200)

The AsyncImage view takes an URL as an argument. You can use the URL(string:) constructor to create an URL with any link to an image on the internet.

Now we have two closures: the first one containing the fetched image (once it's loaded) and the second one containing a placeholder View which is on screen while the Image is loading.

Now we only need to do 3 things:

  • Add the .resizeable() modifier to the image to make the image scale with the available space. Otherwise it would render in its original resolution.
  • Set the aspect ratio's content mode to either .fill or .fit. When set to fill the image will scale to fill all the available space given to the view while preserving the original aspect ratio of the image. Fit on the other hand would make sure to fit the whole image into the space given to the view which may result in whitespace either on the top and bottom or leading and trailing side of the image.
  • To explicitly set a size just add a .frame() modifier with the desired values to the AsyncImage. This is also the place to add some padding if needed.

Play around a bit and have fun coding!

Another article you might like: