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

标签 ios swift uitabbarcontroller uinavigationbar

当用户单击通知时,我需要导航到通知 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/

相关文章:

ios - 用 swift 在段落周围画框

android - 如何建立从 iOS Safari 到 Android Chrome 的 Webrtc 连接

ios - 我的滚动图像按钮无法快速运行

ios - 如何在 Apple Watch OS 2 上使用 iPhone 的核心数据?

ios - 向 TabBar 应用程序添加 UI 导航

ios - 将 Controller 添加到 UITabBarController 而没有新项目出现在选项卡栏中

objective-c - 如何在 iOS 上创建标签栏?

ios - 如果我将手指从我的节点移开并进入 GameView,为什么我的节点会停止旋转?

iphone - 在循环中创建的 UIButton 不可点击

ios - 如何将下拉菜单添加到 iOS 中的导航栏标题