在我的iOS应用中,我想在推送通知事件到来时打开一个新的视图控制器。我尝试在AppDelegate.swift内部执行以下操作来处理导航。

let friendStoryboard = UIStoryboard(name: "Profile", bundle: nil)
let friendsVC = friendStoryboard.instantiateViewController(withIdentifier: "FriendsViewIdentifier") as! FriendsViewController
let backItem = UIBarButtonItem()
backItem.title = ""
self.window?.rootViewController?.navigationItem.backBarButtonItem = backItem
self.window?.rootViewController?.navigationController?.pushViewController(friendsVC, animated: true)

但是它仍然不能处理View Controller的导航。我该如何工作?

因此在这种情况下,我的视图控制器层次结构不包含UiNavigationController。层次结构如下。

ios - 从AppDelegate内部执行pushViewController-LMLPHP

最佳答案

否则,您会得到答案。

if let friendStoryboard: UIStoryboard = UIStoryboard(name: "Profile", bundle: nil) {
        if let friendsVC = friendStoryboard.instantiateViewController(withIdentifier: "FriendsViewIdentifier") as? FriendsViewController {

            let backItem = UIBarButtonItem()
            backItem.title = ""
            self.window?.rootViewController?.navigationItem.backBarButtonItem = backItem

            if let navController = self.window?.rootViewController as? UINavigationController {
                navController.pushViewController(friendsVC, animated: true)
            } else if let tabController = self.window?.rootViewController as? UITabBarController {

                if let tabViewControllers = tabController.viewControllers {

                    if let navController = tabViewControllers.first as? UINavigationController {
                        navController.pushViewController(friendsVC, animated: true)

                    } else {
                        print("tabViewControllers.first as? UINavigationController not found")
                    }

                }  else {
                    print("tabViewControllers count is zero")
                }

            } else {
                print("UINavigationController & UITabBarController not found at self.window?.rootViewController")
            }

        } else {
            print("FriendsViewController not found")
        }

    } else {
        print("friendStoryboard not found")
}

10-08 06:26