AsyncImage inside ForEach Loop

559 Views Asked by At

I'm using stock AsyncImage to load an image from Firebase Storage to my app. I'm using two exactly same fragments of code to load the same image however the app compiles only when there is only the first fragment, the second one causes crash. The only difference between them is that I want to use the second one to display several same images in ForEach Loop.

The first fragment:

HStack {
    if let profilePicturePhotoURL = profileViewModel.profilePicturePhotoURL {
        AsyncImage(url: profilePicturePhotoURL) { phase in
            if let image = phase.image {
                image
                    .resizable()
            } else {
                Image(uiImage: UIImage(named: "blank-profile-hi")!)
            }
        }
    } else {
        Image(uiImage: UIImage(named: "blank-profile-hi")!)
    }
    
    Text("What do you want to share?")
        .frame(width: screenWidth * 0.6, height: screenHeight * 0.1)
}
.padding(.leading, screenWidth * 0.05)

The second fragment:

if homeViewModel.posts != nil {
    ForEach(homeViewModel.posts!) { post in
        VStack {
            Rectangle()
                .foregroundColor(Color(uiColor: .systemGray6))
                .frame(width: screenWidth, height: screenHeight * 0.02)
            
            HStack {
                if let profilePicturePhotoURL = profileViewModel.profilePicturePhotoURL {
                    AsyncImage(url: profilePicturePhotoURL) { phase in
                        if let image = phase.image {
                            image
                                .resizable()
                        } else {
                            Image(uiImage: UIImage(named: "blank-profile-hi")!)
                        }
                    }
                } else {
                    Image(uiImage: UIImage(named: "blank-profile-hi")!)
                }

Leaving only

Image(uiImage: UIImage(named: "blank-profile-hi")!)

as the image of the second fragment makes images display properly.

0

There are 0 best solutions below