iOS Swift Navigate to certain ViewController progr

2020-01-29 18:46发布

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?

3条回答
贪生不怕死
2楼-- · 2020-01-29 18:59

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

查看更多
冷血范
3楼-- · 2020-01-29 19:09

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()
查看更多
倾城 Initia
4楼-- · 2020-01-29 19:18

The topController was already my TabBarController in this case!

查看更多
登录 后发表回答