Using AsyncImage in SwiftUI
Note – This post goes along with this video: https://youtu.be/uHjDC8tPzPY
AsyncImage is a great and easy way to load images from URLs into a SwiftUI view! It’s super easy to implement and it works great.
Getting Started
To just load an image without any customization, you can do the following:
AsyncImage(url: URL(string: "https://example.com/image"))
As is, this image will show a grey placeholder while the image loads, to further customize this and the image, keep reading!
Note – make sure to replace “https://example.com/image” with a link to your image
Further Customization
In order to further customize the image, we can use the initializer for AsyncImage:
init(url:
Using this initializer, we can make our image resizable, scale it, and add a placeholder for it as the image loads.
AsyncImage(url: URL(string: "https://example.com/image")) { image in image } placeholder: { }
Now, you can do the following:
AsyncImage(url: URL(string: "https://example.com/image")) { image in image .resizable() .scaledToFit() .frame(width: 300, height: 300) } placeholder: { Color.purple .frame(maxWidth: 300, maxHeight: 300) .cornerRadius(25) }
In the code above, I made the image itself resizable and scaled to fit , and the frame of the image is 300×300. While the image loads, the user will see the placeholder, which is just the color purple.
Note – You can also use another view in the PlaceHolder, such as a Progress View
Full Code
Following is all the code that I used in the video tutorial:
Final Thoughts
This was my first ever attempt at writing a tutorial, and it was fun! I’m hoping this helped you with AsyncImage. If you have any feedback, please leave it in the comments below! If you have any questions regarding this post, you can reach me through my discord server (http://bit.ly/discordvedantapps), YouTube Channel, or through the comments here! Thanks for reading!
Very Cool!