top of page
Writer's pictureHui Wang

21. SwiftUI: How to download and display network images using image view


YouTube:




Source Code:

import SwiftUI

struct ContentView: View {
    @State private var remoteImage: UIImage? = nil
    let placeholderImage = UIImage(named: "placeholder")
    
    var body: some View {
        VStack {
            Image(uiImage: self.remoteImage ?? placeholderImage!)
                .onAppear(perform: fetchRemoteImage)
        }
    }
    
    func fetchRemoteImage() {
        guard let url = URL(string: "https://i.pinimg.com/736x/b1/94/50/b19450bfc8a43edab7f706a16e070001.jpg") else { return }
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let image = UIImage(data: data!) {
                self.remoteImage = image
            } else {
                print(error ?? "")
            }
        }.resume()
    }
}

#if DEBUG
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif

 

Follow me on:

Comments


bottom of page