user2636197 user2636197 - 29 days ago 11
Swift Question

Swift ios send user to a specific ViewController in tab based application

I want to send a user to a specific ViewController in my app once a notification is clicked.

I now that I can do something like this:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController = storyboard.instantiateViewControllerWithIdentifier("Home") as? HomeViewController
presentedVC?.presentViewController(destinationViewController!, animated: true, completion: nil)


But my app has a tab bar and looks like this

Tab bar

tab1: navigationController -> VC1

tab2: navigationController -> VC2 -> HomeVC

tab: navigationController -> VC3

Each tab has a navigationController as a infront of it.

So how can I send the user to HomeVC? I must first select tab 2 then the navigation controller then push the user tvice:

tab2: navigationController -> VC2 -> HomeVC

And the other problem, if there any way to tell if the user is already in HomeVC? I dont want to send the user to the same VC if his already there.

Answer

You must have access to your UITabbarController in you UIApplicationDelegate or wherever you're handling the notification tap.

let tabBar:UITabBarController = self.window?.rootViewController as! UITabBarController //or whatever your way of getting reference is

So first you'll get the reference to UINavigationController in your second tab like this:

let navInTab:UINavigationController = tabBar.viewControllers?[1] as! UINavigationController

Now push your home view at second tab's navigation controller:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController = storyboard.instantiateViewControllerWithIdentifier("Home") as? HomeViewController
navInTab.pushViewController(destinationViewController!, animated: true)

And finally switch your tab to second to show the just pushed home controller

tabBar.selectedIndex = 1

Keep in mind, this answer assumes that your application has already set the tab bar as the root view controller of application window prior handling the notification tap.