skip to Main Content

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?

3

Answers


  1. 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)
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. I would personally build a custom one with your needs.
    I’ve recently tried it to get more in touch with combine publishers and it’s quite simple to get something decent, if you want to try/contribute/take it as example, feel free: Simple iOS 13 AsyncImage

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search