如果通知已打开,如何直接进入特定的视图控制器

我有一个UITabBarController在一个选项卡中显示聊天表。 如果用户点击一行,将显示一个视图控制器,显示最新的消息。

现在我正在介绍推送通知。 如果用户打开推送通知,所需的行为是自动进入聊天室。 虽然有关于如何处理这些用例的大量信息,但是我没有成功实现它。

这是我的代码到目前为止:

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. if (!isUserLoggedIn()) { // show login vc } else { let protectedController = mainStoryboard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController if let notificationPayload = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary { if let chatId = notificationPayload["chatId"] as? String { print(chatId) // show chat VC } } window!.rootViewController = protectedController window!.makeKeyAndVisible() } let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. } application.registerForRemoteNotifications() return true } 

打印语句将永远不会被调用,但这可能是由于应用程序在打开通知之前已完全closures。

didFinishLaunchingWithOptions不一定被调用,当你点击一个通知,只有当你的应用程序不在内存中了

在您的willFinishLaunchingWithOptions函数中,设置currentNotificationCenter的委托

 func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { UNUserNotificationCenter.current().delegate = self } 

确保你的AppDelegate实现UNUserNotificationCenterDelegate与你相关的UNUserNotificationCenterDelegate

 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo if let chatID = userInfo["chatID"] as? String { // here you can instantiate / select the viewController and present it } completionHandler() } 

更新以回答您的后续问题:如何将UIViewController添加到UITabbarControllerUINavigationController

为了实例化您的ViewController并将其添加到您的UITabbarController

 let myViewController = MyViewController() guard let tabbarController = self.window.rootViewController as? UITabbarController else { // your rootViewController is no UITabbarController return } guard let selectedNavigationController = tabbarController.selectedViewController as? UINavigationController else { // the selected viewController in your tabbarController is no navigationController! return } selectedNavigationController.pushViewController(myViewController, animated: true) 

当用户点击通知时,应用程序委托的callback方法是:

应用:didReceiveRemoteNotification:fetchCompletionHandler:

有关来自Apple的通知的更多信息。

你应该把你的代码放在这个方法里面。

您也可以创build路由器类(NSObject的子类),它将显示聊天视图控制器,并负责在应用程序中的视图控制器之间导航。

这是一个很好的方式将这个逻辑封装到单独的类中,而不是保留在AppDelegate类中。