4

Is it possible to reset the root view controller? With reset I mean resetting it to its initial state so viewDidLoad will be called again. I'm using a UITabBarController and when I logout I want all the tabs previously loaded to be unloaded.

Daniel Tovesson
  • 2,550
  • 1
  • 30
  • 41
  • Create new instance and set to root view controller may help – Prashant Tukadiya Jul 25 '17 at 12:29
  • Why not use `viewWillAppear` to reset the state? – Hodson Jul 25 '17 at 12:29
  • Possible duplicate of [Does viewDidload method call again on going back to a screen in navigation controller?](https://stackoverflow.com/questions/33778426/does-viewdidload-method-call-again-on-going-back-to-a-screen-in-navigation-contr) – Himanth Jul 25 '17 at 12:29
  • How is my question a duplicate @himanth? I asked how to reset the root view controller, not how and when viewDidLoad is called – Daniel Tovesson Jul 25 '17 at 12:39
  • 1
    @DanielTovesson Dont be panic bro, others will understand your quest according to your content or may be some get misunderstanding from it. – dahiya_boy Jul 25 '17 at 12:42
  • @DanielTovesson By the way it is possible. You need to set your required `UIViewController` after the logout as the rootViewController of NavigationController. – dahiya_boy Jul 25 '17 at 12:44

3 Answers3

6

You can do this by setting the instance of TabBarController to rootViewController on logout action.

Swift 3:

let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let tabBarController = storyBoard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController
UIApplication.shared.keyWindow?.rootViewController = tabBarController
UIApplication.shared.keyWindow?.makeKeyAndVisible()

Objective C:

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UITabBarController *tabBarController = [storyBoard instantiateViewControllerWithIdentifier:@"TabBarController"];
[[[UIApplication sharedApplication] keyWindow] setRootViewController:tabBarController];
[[[UIApplication sharedApplication] keyWindow] makeKeyAndVisible];
Rahul Kumar
  • 3,009
  • 2
  • 16
  • 22
1

If you are using navigation controller on Tabbarcontroller then navigate to that navigation controller otherwise go to Tabbarcontroller as-

 let appDelegate = UIApplication.shared.delegate as! AppDelegate
 let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
 let tabBar = mainStoryboard.instantiateViewControllerWithIdentifier("TabBarController") as! TabBarController
 appDelegate.window?.rootViewController = tabBar
 appDelegate.window?.makeKeyAndVisible()
Jack
  • 13,571
  • 6
  • 76
  • 98
0

Set view property of UIViewController to nil

UIApplication.shared.keyWindow?.rootViewController?.view = nil

it will force UIViewController to init his life cycle from a beginning after next call to self.view

Taras Chernyshenko
  • 2,729
  • 14
  • 27