当用户单击通知时,我需要导航到通知 Controller 。因此我需要从 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 条件第二次失败(获取零值)。
如果有人知道请帮助我
最佳答案
第一次收到通知时,将 UINavigationController 分配给 rootViewController:
let nav: UINavigationController = UINavigationController()
self.window?.rootViewController = nav
因此,当您收到第二个通知时,您的 rootViewController 不再是 UITabbarController,而是 UINavigationController 的实例,因此进行强制转换
let cu = self.window?.rootViewController as? UITabBarController
将会失败。
您不应该创建新的 UINavigationController。相反,您应该推送 View Controller
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
}
关于ios - 当应用程序处于后台状态时单击通知时导航栏消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55136301/