Asynchronously Loading Images in SwiftUI

Image for post
Image for post

One of the questions I keep getting asked from my Udemy students is that how to load images in SwiftUI. SwiftUI includes the Image view but unfortunately, Image currently does not support url as an argument.

In this post, we will implement a custom SwiftUI view which will be responsible for fetching and displaying the image using the url.

Let’s get started!

Implementation

Before implementing a custom Image component for SwiftUI, we will write a service which will be responsible for fetching the image. The ImageLoader service will be responsible for downloading the image using the url.

Now let’s implement the URLImage view in SwiftUI. The URLImage will be responsible for taking a url as an argument and then utilizing the ImageLoader service to download and display the image.

Now, that we have URLImage implemented let’s see how we can use it.

And the result is shown below:

Image for post
Image for post

Happy coding!

If you liked this post and want to support my work then check out my course on SwiftUI below:

iOS Developer, speaker and educator. Top Udemy and LinkedIn instructor. Lead instructor at DigitalCrafts. https://www.udemy.com/user/mohammad-azam-2/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store