Josh O'Connor Josh O'Connor - 5 months ago 8
Swift Question

Calling upon the previous view controller in Swift

I am trying to call upon the root controller and I don't know the code to call upon it. I'm using a conditional and which will check what the previous view controller was, and a block of code will run depending on what it was. Here is my code:

SecondViewController

override func viewDidLoad ( ) {
super.viewDidLoad ( )

let previousController = storyboard!.instantiateViewControllerWithIdentifier ("firstViewController") as? FirstViewController

//HELP IN LINE BELOW
//if root view controller == previousController {
//run some code
//}
}

Answer
let stack = self.navigationController.viewControllers
if (stack.count > 1) {
    let previousController = stack[stack.count-2]
}

Or if you don't have a navigation controller

let previousController = self.presentingViewController

Also, just to be clear, the root view controller will be the first view controller in the stack, i.e:

self.navigationController.viewControllers.firstObject

or

var previousController : UIViewController = self
var rootController : UIViewController?
do {
    var rootViewController = previousController
    var previousController = rootViewController.presentingViewController
} while (previousController != nil)