我有一个问题想解决。
我有一个标签栏,如我的rootViewController这样定义
window?.rootViewController = MainTabViewController()
我需要从带有以下代码段的远程推送通知中推送到viewController,但是我的应用程序崩溃了,我的cannot cast MainTabViewController to UINavigationViewController崩溃了,因为MainTabViewController并未嵌入NavigationViewController中,所以我无法进行这种投射。解决此问题的最佳方法是什么?

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    let userInfo = response.notification.request.content.userInfo

    if let type = userInfo["type"] as? String, let data = userInfo["data"] as? String, let title = userInfo["title"] as? String {
        let params = ["type": type, "data": data, "title": title]
        Analytics.AddEvent(title: "Notification Open", params: params)

        let backItem = UIBarButtonItem()
        backItem.title = ""
        let navVC = window?.rootViewController as! UINavigationController
        NSLog("Controller Type: \(navVC.description)")
        navVC.navigationController?.navigationBar.tintColor = .black
        navVC.navigationItem.backBarButtonItem = backItem
        if type == "category_product"{
            //Show product list
            var params = [String: String]()
            params["CategoryName"] = title
            params["CategoryId"] = data
            Analytics.AddEvent(title: "Category Opened", params: params)

            let vc = ProductListingVC()
            vc.categoryName = title
            vc.category_id = data
            vc.hidesBottomBarWhenPushed = false
            navVC.pushViewController(vc, animated: true)
        }

最佳答案

您具有tabBarController作为rootViewController,并且将其强制类型转换为导航控制器,这是代码中的问题。您需要将rootViewController强制转换为MainTabViewController,然后在MainTabViewController上找到选定的选项卡(如果您有导航控制器),然后将ProductListingVC控制器推入该导航控制器,否则需要显示ProductListingVC

10-07 20:43