How do I load images asynchronously in SwiftUI with Swift?

Loading images asynchronously in SwiftUI is essential for maintaining a smooth user interface, especially when dealing with large image files or network resources. By using asynchronous loading, you can prevent blocking the main thread and ensure your app remains responsive.

SwiftUI, async image loading, Swift, UIImage, Combine

This guide explains how to load images asynchronously using SwiftUI in Swift. It covers best practices and includes a code example for implementation.

        struct AsyncImageView: View {
            @State private var image: UIImage?
            @State private var isLoading = true
            
            let url: URL
            
            var body: some View {
                Group {
                    if let image = image {
                        Image(uiImage: image)
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                    } else {
                        ProgressView()
                    }
                }
                .onAppear {
                    loadImage()
                }
            }
            
            private func loadImage() {
                isLoading = true
                URLSession.shared.dataTask(with: url) { data, response, error in
                    if let data = data, let loadedImage = UIImage(data: data) {
                        DispatchQueue.main.async {
                            self.image = loadedImage
                            self.isLoading = false
                        }
                    }
                }.resume()
            }
        }
        

SwiftUI async image loading Swift UIImage Combine