I'm trying to return to a previous view controller but I'm running to issues that (to my understanding) shouldn't be happening.
A short description of what I'm trying to do: I have 4 view controllers: A, B, C and D. The basic UI flow is A -> B -> C -> D. After finishing work in C, I want to return back to B.
My code:
let viewControllerArray = self.navigationController?.viewControllers
for(var i=0;i<viewControllerArray?.count;i++){
if(viewControllerArray![i].isKindOfClass(InventoryListViewController)){
self.navigationController?.popToViewController(viewControllerArray![i], animated: true)
}
}
This all works fine if B still exists on the navigationcontroller's stack. If B has been removed from the stack (due to memory-related reasons) it gives me a Tried to pop to a view controller that doesn't exist error (obviously). The thing I'm confused about is that shouldn't the If-statement prevent the popToViewController method from getting called if B doesn't exist on the stack anymore?
To create a new view controller, select File->New->File and select a Cocoa Touch Class. Choose whether to create it with Swift or Objective-C and inherit from UIViewController . Don't create it with a xib (a separate Interface Builder file), as you will most likely add it to an existing storyboard.
The best way to prevent a crash is by optional unwrapping. Try this code and let me know if it solves the issue.
let allVC = self.navigationController?.viewControllers
if let inventoryListVC = allVC![allVC!.count - 2] as? InventoryListViewController {
self.navigationController!.popToViewController(inventoryListVC, animated: true)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With