Home > other >  AsyncImage not displaying image URL when passed into view
AsyncImage not displaying image URL when passed into view

Time:09-28

This child view is not displaying image URLs passed in from a parent view. Child view:

struct PostImageView: View {

  var postImage: String

  var body: some View {
      AsyncImage(url: URL(string: postImage)) { image in
          image
              .resizable()
              .aspectRatio(contentMode: .fit)
      } placeholder: {
          Text("IMAGE URL: \(postImage)")
          ProgressView()
      }
      .ignoresSafeArea()
  }
}
  • The Text("IMAGE URL: \(postImage)") is displaying the image URL on the view during loading state
  • Adding a static image URL displays the image: AsyncImage(url: URL(string: "https://url-to-image"))

The parent view relies on an ObservableObject to determine when to display the view containing AsyncImage:

class ImageDetail: ObservableObject {
    @Published var imageUrl = ""
    @Published var showImageDetail: Bool = false
}

This part of the parent view then navigates to the child view and passes the image URL:

 NavigationLink(destination: PostImageView(postImage: imageDetail.imageUrl), isActive: $imageDetail.showImageDetail) {
    EmptyView()
 }

When showImageDetail is true, the imageUrl value contains a valid image URL, which is then passed into the PostImageView containing AsyncImage.

The imageUrl value is being successfully passed as per the Text("IMAGE URL: \(postImage)") output mentioned above.

CodePudding user response:

After some testing, it appears that AsyncImage is silently failing when an insecure http URL is passed in from the parent.

I've resolved this by adding a function to detect insecure http URLs and convert them to https URLs instead.

Strangely, there is an explicit error about not allowing insecure URLs when using a static URL within the child view, but not when passing from parent.

CodePudding user response:

If you really need to use http instead of https, it's necessary to change NSAppTransportSecurity in you info.plist

But, looks like you've managed to solve the problem without using http, which is better.

  • Related