'Swift 5 - Trying to dismiss all viewcontrollers with navigations and modal presents

im trying to dismiss all viewcontrollers after a few seconds. I found some solutions for this, but doesnt work for me.

I have 6 view controllers, A, B, C are navigations controllers, and D, E , F use modal presentations. I want back to the initial view controller -> A

This is my code Last View Controller:

    viewModel.result
        .observe(on: MainScheduler.instance)
        .withUnretained(self)
        .subscribe(onNext: { owner, result in
            
            let vm = ResultViewModel(state: result)
            let vc = ResultViewController(with: vm)
            vc.modalPresentationStyle = .fullScreen
            owner.present(vc, animated: true)
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                self.view.window!.rootViewController?.dismiss(animated: false, completion: nil)    
            }
            
        }).disposed(by: disposeBag)

When I try to do this, the app crashes saying window is nill.

This is my AppDelegate:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  
    let window = UIWindow(frame: UIScreen.main.bounds)
    self.window = window
    let mainViewModel = MainViewModel()
    let mainViewController = MainViewController(with: mainViewModel)
    let navigationController = UINavigationController()
    navigationController.viewControllers = [mainViewController]
    
    window.rootViewController = navigationController
    window.makeKeyAndVisible()
    
    return true
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source