SwiftUI_visionOS_Note

AsyncImage

May 7, 2024
1 min read|

Asynchronously download image from URL

  • From internet to the device

let url = URL(string: "")

AsyncImage(url: url)
swift

When the view appear, AsyncImage will read the data and put it inside the container. It will fetch the data every time we run the view.

  AsyncImage(url: url)
                .frame(width: 100, height: 200)
swift

Image is bigger than the frame size, so other outside part will be cut off.

We can use url, content and placeholder to modify the image

            AsyncImage(url: url, content: { returnedImage in
                returnedImage
                    .resizable()
                    .scaledToFit()
                    .frame(width:100, height: 100)
                    .clipShape(RoundedRectangle(cornerSize: CGSize(width: 20, height: 10)))
            }, placeholder: {
                ProgressView()}
            )
swift

Now returnedImage can use the modifier properly just like Image()

Phase completion

            AsyncImage(url: url) { phase in ...}
swift

AsyncImagePhage has an empty, success and failure state.

            AsyncImage(url: url) { phase in
                switch phase {
                    
                case .empty:
                    ProgressView()
                    
                case .success(let returnedImage):
                    returnedImage
                        .resizable()
                        .scaledToFit()
                        .frame(width:300, height: 300)
                case .failure(let error):
                    Image(systemName: "questionmark")
                        .font(.headline)
                    
                default:
                    Image(systemName: "questionmark")
                        .font(.headline)
                }
            }
swift

if url string is empty, it will show progressView(), else successful, it will return the Image, else it fails will show the question mark

Subscribe to our newsletter

Get the latest news and updates from our team