Load asynchronous images from URL using SwiftUI
As of WWDC 2021 Apple introduced lots of new async features including asyncImage in SwiftUI. This allows for you to load an image from URL without writing all that boilerplate we used to write.
AsyncImage(url: URL(string: "https://miro.medium.com/max/1138/1*6-G_o5PZSzppyfdLTbFu-A.png")) { image in
image.resizable()
} placeholder: {
Color.white
}
.frame(width: 250, height: 250, alignment: .center)
The AsyncImage view takes in a URL parameter to locate image, then a closure to provide preferences such as resizable, fixedsize, etc. Then a placeholder which takes in a View. In this example we provide the URL to a Swift Logo, then we provide the closure to say we want the image to be resizable, or any other properties you want, finally we provide the placeholder view. That’s it you have yourself a very preferment image view that will only load once it appears on the screen.
Discoveries after Unit Testing
I did some unit tests on the new async image view, and I learn that if their is duplicate images it will cache these images for the next time it needs to load them assuming you haven’t closed the app that is. So if you have a list of the same image it won’t reload the image for each row, instead it will pull the image from cache. How cool is that.