iOS Swift Navigate to certain ViewController programmatically from push notification

喜你入骨 提交于 2019-12-17 14:56:18

问题


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!



来源:https://stackoverflow.com/questions/43058261/ios-swift-navigate-to-certain-viewcontroller-programmatically-from-push-notifica

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!