我正在编写聊天应用程序。我想在后台获取我的消息。这将是连续的。这就是为什么我将使用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(layout:layout)之类的原因。其实我不想要那个。
谢谢。

最佳答案

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

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")
    }

}

关于swift - 如何从TabBar到达NavigationController上的rootViewController?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55495144/

10-13 04:41