1

In the scenario where you have a viewController which you want to present as root view above everything else what is the right way to do this?

let Storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let MY_VIEW = Storyboard.instantiateViewControllerWithIdentifier("VIEWID")


//Is this the right way?
UIApplication.sharedApplication().delegate.window?.rootViewController?.presentViewController(MY_VIEW, animated: true, completion: nil)


//Or this?     
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(MY_VIEW, animated: true, completion: nil)

In other words why would you use UIApplication.sharedApplication().delegate.window? over UIApplication.sharedApplication().keyWindow?.rootViewController? and in what scenarios? What would be the pros/cons of using one or the other?

jscs
  • 63,694
  • 13
  • 151
  • 195
ke3pup
  • 1,835
  • 4
  • 36
  • 66
  • 1
    read differences : [diffrences in keyWindow & Window](http://stackoverflow.com/questions/21698482/diffrence-between-uiapplication-sharedapplication-delegate-window-and-u) – Chandan Jul 20 '16 at 04:43

2 Answers2

1

You can do as follow.

 let rootController = storyboard.instantiateViewControllerWithIdentifier("VIEWID") as! SplashVC

        if self.window != nil {
            self.window!.rootViewController = rootController
        }

advantage of this is not getting crash when window is nil.

Another way is that(Most secure way i think)

   let navigationController:UINavigationController = storyboard.instantiateInitialViewController() as! UINavigationController
   let rootViewController:UIViewController = storyboard.instantiateViewControllerWithIdentifier("VIEWID") as! LoginVC
   navigationController.viewControllers = [rootViewController]
   self.window?.rootViewController = navigationController
Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65
0
           let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let viewController: MainViewController = storyboard.instantiateViewControllerWithIdentifier("MainViewController") as! MainViewController

            let rootViewController = self.window!.rootViewController as! UINavigationController
            rootViewController.pushViewController(viewController, animated: true)
shan
  • 136
  • 7