1

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
     //}
}
Moxy
  • 4,162
  • 2
  • 30
  • 49
Josh O'Connor
  • 4,694
  • 7
  • 54
  • 98
  • `instantiateViewControllerWithIdentifier` will create each time a new view controller. What are you trying to achieve? – Moxy May 11 '15 at 20:42
  • possible duplicate of [How do you share data between view controllers and other objects in Swift?](http://stackoverflow.com/questions/29734954/how-do-you-share-data-between-view-controllers-and-other-objects-in-swift) – nhgrif May 11 '15 at 23:19

1 Answers1

8
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)
Danny Bravo
  • 4,534
  • 1
  • 25
  • 43