我有一个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
}
永远不会调用print语句,但这可能是因为应用程序在打开通知之前已完全关闭。
答案 0 :(得分:1)
didFinishLaunchingWithOptions
不一定被调用,只有当您的应用不在内存中时
在appDelegate的willFinishLaunchingWithOptions
功能中,为currentNotificationCenter设置委托
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
UNUserNotificationCenter.current().delegate = self
}
确保您的AppDelegate
实施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
UINavigationController
添加UITabbarController
为了实例化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)
答案 1 :(得分:0)
当用户点击通知时,app delegate的回调方法是:
application:didReceiveRemoteNotification:fetchCompletionHandler:
有关通知from Apple的更多信息。
您应该将代码放在此方法中。
此外,您还可以创建路由器类(NSObject的子类),它将显示聊天视图控制器,并将负责应用程序中视图控制器之间的导航。
这是一种很好的方式将这个逻辑封装到单独的类中,而不是将它保存在AppDelegate类中。