Load an image from URL in SwiftUI


In this SwiftUI programming tutorial, you are going to learn how to load a remote image from an external URL on the internet and show it in our app.

SwiftUI already has AsyncImage that can download and then display the image from an URL. All we have to do is just passing the URL in the AsyncImage.

Below is given how we can achieve this task:

AsyncImage(url: URL(string: "https://secure.gravatar.com/avatar/f867cbebbb6832e5801b3b2f5b6a5dc3?s=256&d=mm&r=g"))

Below is how it will show the image on the iPhone 13 pro simulator of Xcode:

iPhone 13 pro

In our code, we have used URLs to access the URL of the image.

Below is another example of using the AsyncImage where we make our image resizable to fit the screen and keep the actual aspect ratio:

  
AsyncImage(url: URL(string: "https://secure.gravatar.com/avatar/f867cbebbb6832e5801b3b2f5b6a5dc3?s=256&d=mm&r=g")) { image in
    image.resizable().aspectRatio(contentMode: .fit)
} placeholder: {
    Color.green
}

As you can see, we have also set a placeholder background color to green so that, it will show the green-colored placeholder until the image is downloaded and visible.

We can also set the width and height of our image, set rounded corners and many more with the image added using AsyncImage:

AsyncImage(url: URL(string: "https://secure.gravatar.com/avatar/f867cbebbb6832e5801b3b2f5b6a5dc3?s=256&d=mm&r=g")) { image in
    image.resizable().aspectRatio(contentMode: .fit)
} placeholder: {
    Color.green
}
.frame(width: 200, height: 200)
.clipShape(RoundedRectangle(cornerRadius: 18))

Now we have set the image width and height to 200 and set the rounded corner with the value 18. If we run our code in the simulator, then it will show the result that you can see in the figure below:

iPhone 13 pro simulator