I want to check whether a viewcontroller is present in a navigation stack or not. If it is present, I need to pop it otherwise I need to push it to the navigation stack. I have tried the following code. If it is not present, control is transfering to the else block but I'm unable to navigate to the screen. Please help me
for aViewController in viewControllers! {
if aViewController is TabProfileViewController {
self.navigationController?.popToViewController(aViewController, animated: true)
}
else {
let lvc = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController
self.navigationController?.pushViewController(lvc!, animated: true)
}
}
You're checking it in every loop, so if one time the first condition is true maybe it can become false in next iteration, so it will pop and push. try following code:
if let viewController = viewControllers?.first(where: { $0 is TabProfileViewController }) {
navigationController?.popToViewController(viewController, animated: true)
} else {
let lvc = storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController
navigationController?.pushViewController(lvc!, animated: true)
}