Last updated on March 9, 2023
In WWDC 2021, Apple introduce AsyncImage as a way to download and display remote images from tthe internet. It is as simple as passing in a String
into an URL
.
This is definitely a very joyful news as the usual implementation always relies on a third party SDK like Kingfisher and etc to load a remote image.
Prerequisites
To follow along this tutorial, you’ll need some basic knowledge in:
- A basic familiarity with Swift.
- At least Xcode 13
- iOS 15+
Setting up the AsyncImage
You will create a var
to hold a remote image link. Here, you will see a Tesla image.
private let tesla = "https://www.carshowroom.com.au/media/21484061/2020-tesla-roadster-01.jpg"
Within the VStack
, you will embed AsyncImage
and adjust the scale
parameter according to your need. Any number larger than 1 will make the image smaller.
VStack {
AsyncImage(url: URL(string: tesla), scale: 5.0)
}
Setting up the Placeholder
This image contains a ProgressView
but when the simulator is being recorded, the ProgressView
surprisingly disappear.
Loading a remote image could be a problem if the user’s connectivity is slow. You don’t want to show a blank screen, this will further confuse the users on what is happening. You can instead show a placeholder probably like a loading indicator.
You can achieve that with AsyncImage
.
AsyncImage(url: URL(string: tesla)) { image in
// 1
image
.resizable()
.scaledToFit()
} placeholder: {
ZStack {
// 2
Color.gray
// 3
VStack(spacing: 20) {
// 4
ProgressView()
// 5
Text("Loading...")
.foregroundColor(Color.white)
}
}
}
// 6
.frame(width: 400, height: 300)
- This will resize the image to fit the space provided and scale the image to fit.
- The most bottom stack is a view with a gray background color signifying the placeholder.
- On top of the stack, there is a
VStack
with more components embed within vertically. ProgressView
will be shown on top of the gray placeholder.Text
showing loading oon top of the gray placeholder below theProgressView
.- The size of the frame which include width and height.
Where to go From Here
SwiftUI has definitely bring the animation to a whole new level and also ease of use. I love SwiftUI! Check out more articles that I’ve wrote about SwiftUI.
Comments are closed.