Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 566
Paul T. Avatar asked Jul 18 '20 14:07

Paul T.


1 Answers

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

NavigationView { content }.navigationViewStyle(StackNavigationViewStyle())

like image 72
druid_sf Avatar answered Sep 26 '22 10:09

druid_sf