如何从TabBar到达NavigationController上的rootViewController?

时间:2019-04-03 12:24:39

标签: swift

我正在编写聊天应用程序。我想在后台获取我的消息。这将是连续的。这就是为什么我将使用 performFetchWithCompletionHandler 的原因(如果您知道更好的方法可以为我提供服务)。我的 rootViewController tabBar 。但是我必须将此代码用于其他控制器,并且无法从 AppDelegate 访问该控制器。

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if let tabbarController = window?.rootViewController as? CustomTabBarController{
        if let postController = tabbarController.navigationController?.viewControllers.first as? PostsController{
            print("itsWorking")
        }
    }
}


override func viewDidLoad() {
    super.viewDidLoad()
    //This is my rootViewController

    let layout = UICollectionViewFlowLayout()

    let postsController = PostsController(collectionViewLayout: layout)
    let gezginController = GezginController(collectionViewLayout: layout)

    let homeNavController = UINavigationController(rootViewController: postsController)
    homeNavController.tabBarItem.title = "Home"
    homeNavController.tabBarItem.image = UIImage(named: "home")

    navigationController?.pushViewController(gezginController, animated: true)
    gezginController.tabBarItem.title = "Gezgin"
    gezginController.tabBarItem.image = UIImage(named: "rocket")

    viewControllers = [homeNavController,gezginController]
}

我想从 AppDelegate 到达 PostController 。但是您必须知道 PostController 是CollectionView,而我正在为此使用布局。这就是为什么我不能在 AppDelegate 上使用 PostController (布局:布局)的原因。其实我不要那个。
谢谢。

1 个答案:

答案 0 :(得分:0)

您需要访问应用程序的共享窗口:

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    if let tabbarController = UIApplication.shared.keyWindow?.rootViewController as? CustomTabBarController,
        let postController = tabbarController.navigationController?.viewControllers.first as? PostsController {
        print("great success")
    }

}