user2636197
user2636197

Reputation: 4122

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.

Upvotes: 1

Views: 1998

Answers (3)

Adil Soomro
Adil Soomro

Reputation: 37729

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.

Upvotes: 4

Anni S
Anni S

Reputation: 2026

You can check which tab is selected by user with the method var selectedIndex: Int. You can check which view controller is present like this self.navigationController?.presentingViewController?.presentedViewController. This will solve your problem.

Upvotes: 0

Eugen Dimboiu
Eugen Dimboiu

Reputation: 2803

Try something like this:

if let tabBarController = window?.rootViewController as? UITabBarController {
  tabBarController.selectedIndex = 1 // in your case the second tab
}

The idea is to switch to get the tab bar instance and switch it to your desired tab (where you have your view controller).

The above code works in AppDelegate / you can easily call it anywhere by getting the tabBarController instance.

Upvotes: 0

Related Questions