SwiftUI randomly crashes on presentationMode?.wrappedValue.dismiss()

1k Views Asked by At

This is how the crash looks like

enter image description here

So it randomly crashes on the UIKit line

UIKitCore
-[UIViewController _ancestorViewControllerOfClass:allowModalParent:] + 44

I have View in default SwiftUI navigation stack:

struct MyView: View {
  @EnvironmentObject var viewModel: MyViewModel
  @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

var body: some View {
    ZStack {
      ......
    }
    .onAppear {
      self.viewModel
        .onViewAppear(presentationMode: self.presentationMode)
    }
  }
}

final class MyViewModel {
  var presentationMode: Binding<PresentationMode>?

  func onViewAppear(presentationMode: Binding<PresentationMode>) {
    self.presentationMode = presentationMode
  }

  func hide() {
    presentationMode?.wrappedValue.dismiss() // crashes after calling this
  }
}

So I push MyView in navigation stack this way:

NavigationLink(
      destination: MyView()
    ) {
      Image(systemName: "plus.circle")
        .font(.title)
    }

And then after user presses a button in MyView after several seconds I call hide() in the MyViewModel. Almost all the time it works but in 5-10% cases it crashes.

1

There are 1 best solutions below

0
On

Fix for me was to set .navigationViewStyle(StackNavigationViewStyle())

NavigationView { content }.navigationViewStyle(StackNavigationViewStyle())