Home > Net >  AsyncImage with URLRequest
AsyncImage with URLRequest

Time:02-24

I am receiving an Image from my server with a post request using URLRequest.

I noticed that the AsyncImage view as for now, does not support a URLRequest as an input.

As for now, I have 2 options in mind:

  1. Using UIImage(data:)
  2. Building a custom AsyncImage something like in this link: https://www.donnywals.com/using-swifts-async-await-to-build-an-image-loader/

Are these really the only alternatives or perhaps I'm missing something?

CodePudding user response:

You can download asyncImage with URL String Exemple:

AsyncImage(url: URL(string: imageURL)){image in
                image
                    .resizable()
                    .frame(width: 75, height: 75)
                    .scaledToFit()
                    .cornerRadius(10)

CodePudding user response:

You can use the .task() modifier to your image in your view, like this:

    @State private var myImage: UIImage? = nil
    
    var body: some View {
        Group {
            if myImage == nil {
                ProgressView()
            } else {
                Image(uiImage: myImage!)
                    .resizable()
                    .scaledToFit()
            }
        }
        .task {
            let downloadedImage = await UIImage(data: myURLRequestHere())) ?? UIImage()      // URLRequest to return data
            DispatchQueue.main.async {
                withAnimation {
                    myImage = downloadedImage
                }
            }
        }
    }

It will work for iOS 15 on.

  • Related