UIImage in Swift only loads after triggering twice

57 views Asked by At

I've setup a button in Swift to retrieve binary data from Core Data as a UIImage, and then pull up a fullscreencover to display the image. When I run the code, the print statement shows displayedImage is not nil, but the optional let binding of image = displayedImage does not evaluate to true, so the Text("No image selected") is shown instead. However, once I close out of the fullscreencover and click the button again, it displays the image correctly.

Here's how displayedImage is instantiated:

@State private var displayedImage: UIImage?

and here's the relevant Button and fullscreencover:

            Button("Show Image") {
                if let insuranceCardData = vehicle.insuranceCard {
                    displayedImage = UIImage(data: insuranceCardData)
                    DispatchQueue.main.async {
                        print("Button - Showing image: \(self.displayedImage != nil)")
                        showingImage = true
                    }
                }
            }
            
            .foregroundColor(.white)
            .padding()
            .background(Color.green)
            .cornerRadius(10)
            .padding()
        } //End of VStack

        .navigationTitle("\(vehicle.make ?? "") Details")
        .fullScreenCover(isPresented: $showingImage) {
            if let image = displayedImage {
                Image(uiImage: image)
                    .resizable()
                    .scaledToFit()
                    .onTapGesture {
                        showingImage = false
                    }
            } else {
                // Fallback view in case there's no image
                Text("No image selected")
                    .onTapGesture {
                        showingImage = false
                    }
            }
        }
    }
}

I have made sure the image from Core Data (vehicle.insuranceCard) is correct, and I've tried loading it within the DispatchQueue.main.async block but get the same result. I've also tried pre-loading the image in a .onappear{} of the vstack, but then displayedImage is always nil. I'm super stumped and new to Swift, but I feel like it has something to do with how Swift refreshes it's variables or something?

0

There are 0 answers