当应用程序处于后台状态时,单击通知时导航栏消失

时间:2019-03-13 07:14:20

标签: ios swift uitabbarcontroller uinavigationbar

当用户单击通知时,我需要导航到通知控制器。因此,我需要从AppDelegate类重定向它们

代码如下:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")

              if  let cu = self.window?.rootViewController as? UITabBarController
              {

            print(cu)
                    let nav: UINavigationController = UINavigationController()

                    self.window?.rootViewController = nav

                    let str = UIStoryboard.init(name: "Main", bundle: nil)

                    let rr = str.instantiateViewController(withIdentifier: "NotificationListViewController")

                    nav.setViewControllers([cu,rr], animated: true)

                }
        }



        // Print full message.
        print(userInfo)

        completionHandler()
    }
}

上述方法有效,是指仅当我第二次尝试时才第一次导航到通知页面。

if条件第二次失败(获取nil值)。

如果有人知道,请帮助我

1 个答案:

答案 0 :(得分:0)

您在第一次收到通知时将UINavigationController分配给rootViewController: let nav: UINavigationController = UINavigationController() self.window?.rootViewController = nav 因此,当您收到第二个通知时,rootViewController不再是UITabbarController,而是UINavigationController的实例,因此进行了强制转换 let cu = self.window?.rootViewController as? UITabBarController将失败。

您不应创建新的UINavigationController。相反,您应该推送视图控制器

if let cu = self.window?.rootViewController as? UITabBarController {
   let str = UIStoryboard.init(name: "Main", bundle: nil)
   let rr = str.instantiateViewController(withIdentifier: "NotificationListViewController")
   cu.pushViewController(rr, animated: true)
}

或转到UITabBarController的适当标签:

if let cu = self.window?.rootViewController as? UITabBarController {
    let notificationsTabIndex = 1 //use proper tab number    
    cu.selectedIndex = notificationsTabIndex
}