-->

iOS Swift Navigate to certain ViewController progr

2020-01-29 18:37发布

问题:

I use push notifications to inform the user about different types of events happening in the app. A certain type of push notification should open a special viewcontroller (f.e a notification about a new chat message does navigate to the chat on click)

To achieve this, i tried the following code inside my app delegate:

func applicationDidBecomeActive(_ application: UIApplication) {
 if var topController = UIApplication.shared.keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
        topController.tabBarController?.selectedIndex = 3
    }
}

It does not move anywhere. What am I missing here?

回答1:

I wrote a simple class to navigate to any view controller in the view hierarchy from anywhere in one line of code by just passing the class type, so the code you'll write will be also decoupled from the view hierarchy itself, for instance:

Navigator.find(MyViewController.self)?.doSomethingSync()
Navigator.navigate(to: MyViewController.self)?.doSomethingSync()

..or you can execute methods asynchronously on the main thread also:

Navigator.navigate(to: MyViewController.self) { (MyViewControllerContainer, MyViewControllerInstance) in
    MyViewControllerInstance?.doSomethingAsync()
}

Here's the GitHub project link: https://github.com/oblq/Navigator



回答2:

This is what you need.
Use your navigation controller to push your notification view controller

    let mainStoryBoard : UIStoryboard       = UIStoryboard(name: "Main", bundle: nil)
    let navigationController : UINavigationController = mainStoryBoard.instantiateViewController(withIdentifier: "MainNavigationController") as! UINavigationController

    let notifcontrol : UIViewController     = (mainStoryBoard.instantiateViewController(withIdentifier: "NotificationViewController") as? NotificationViewController)!

    navigationController.pushViewController(notifcontrol, animated: true)

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()


回答3:

The topController was already my TabBarController in this case!