Search code examples
iosswiftuistoryboardrootviewcontroller

Setting rootViewController then navigate to next view programatically


Initially I have a hierarchy below after login

-> MyCoursesViewController
 -> CourseInfo UITabBarController

If the user closes the app, then re-enters, the rootViewController will be the CourseInfo UITabBarController which is correct. However when the user needs to view a different course (exits the course), they can’t go ‘back’ to MyCoursesViewController because its no longer on the stack.

In AppDelegate:

if (inCourse) {
  let storyboard : UIStoryboard = UIStoryboard(name: “Main”, bundle: nil)
  let courseInfoTabController = storyboard.instantiateViewControllerWithIdentifier(“CourseInfo”) as! UITabBarController
  self.window?.rootViewController = courseInfoTabController
} else {
  let storyboard : UIStoryboard = UIStoryboard(name: “Main”, bundle: nil)
  let myCoursesViewController = storyboard.instantiateViewControllerWithIdentifier(“MyCourses”)
  self.window?.rootViewController = myCoursesViewController
}

Is there some way I can put the MyCoursesViewController as the rootViewController then automatically navigate to Course Info UITabBarController just so the MyCoursesViewController is on the hierarchy incase they hit back (exits the course)?

Alternatively is it better if the user exits the course (hit back), we delete the rootViewController somehow and replace with a new rootViewController? Another option is if we just replace the rootViewController, will the old one be freed from memory or is it still referenced somewhere?

e.g.

CourseInfo UITabBarController is currently still rootViewController but now we swap it out with a new one

 let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
 let myCoursesViewController = mainStoryBoard.instantiateViewControllerWithIdentifier(“MyCourses”) as! ViewController
 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
 appDelegate.window?.rootViewController = myCoursesViewController 

Solution

  • In your AppDelegate you can set your hierarchy. Try with something like:

        let storyboard : UIStoryboard = UIStoryboard(name: “Main”, bundle: nil)
    
        let myCoursesViewController = storyboard.instantiateViewControllerWithIdentifier(“MyCourses”)
    
        if isInCourse{
            let courseInfoTabController = storyboard.instantiateViewControllerWithIdentifier(“CourseInfo”) as! UITabBarController
            let navigationBar = UINavigationController()
            navigationBar.setViewControllers([myCoursesViewController,courseInfoTabController], animated: false)
            self.window?.rootViewController = navigationBar
        }else{
            self.window.rootViewController = myCoursesViewController
        }