Search code examples
iosswiftuiviewcontrolleruinavigationcontroller

popToViewController is not working but popViewController does


Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Tried to pop to a view controller that doesn't exist.'

When using this code

self?.navigationController?.popToViewController(vc2, animated: true)

But when I try to pop simply its working

self?.navigationController?.popViewController(animated: true)

I am pushing this viewController like

navigationController?.pushViewController(vc2, animated: true)

I am not sure, pushing a view means that when I try to do popToViewController. It has a view on top of it. Please help


Solution

  • try this:-

    for obj in (self.navigationController?.viewControllers)! {
        if obj is TestViewController {
            let vc2: TestViewController =  obj as! TestViewController
            vc2.data = data
            self.navigationController?.popToViewController(vc2, animated: true)
            break
        }
    }
    

    Make sure your view controller is added on navigationcontroller stack.