swiftUI is not refresh ui in lower hierarchy

Viewed 24

I have a @Published var showDialog: Bool = false in viewmodel , once it been true , I want to show a dialog , but for some resone it does not show any , and the same code work if I change showDialog in upper Uis

My Main View

 @StateObject  var viewModel = ViewModel.instance


    UploadlingImages( )
     .alert(isPresented: $ViewModel.showDialog) {
      Alert(title:  Text("Content View Alert"),
      message:  Text("Content View Alert"),
    dismissButton: .default(Text("OK")))
    }

Code used Inside view , this is as gallery picker

struct ImagePickerSwiftUI: UIViewControllerRepresentable {
    @SwiftUI.Environment(\.presentationMode) private var presentationMode
   
    @StateObject  var viewModel = ViewModel.instance
    
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePickerSwiftUI>) -> UIImagePickerController {
     
        let imagePicker = UIImagePickerController()
        imagePicker.allowsEditing = false
        imagePicker.sourceType = sourceType
        imagePicker.delegate = context.coordinator

        return imagePicker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePickerSwiftUI>) {

    }

    func makeCoordinator() -> Coordinator {
     
      return  Coordinator(self)
    }

    final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

        var parent: ImagePickerSwiftUI

        init(_ parent: ImagePickerSwiftUI) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
  
            parent.presentationMode.wrappedValue.dismiss()
            
           viewModel.showDialog = true // this line in not updateing ui
        
        }

    }
}
1 Answers

Assuming ViewModel.instance is shared singleton and showDialog is published property, the reason might be in conflict of close/open sheet flows (presentations), so try

parent.presentationMode.wrappedValue.dismiss()

// delay for previous presentation get closed !!
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
   ViewModel.instance.showDialog = true
}
Related