iOS终止/杀死状态下Tab Bar Controller的推送通知跳转处理
iOS应用终止/杀死状态下推送通知跳转解决方案
针对Tab Bar Controller架构的应用,解决终止状态下点击推送无法跳转至指定页面的问题,核心是在App启动阶段正确提取推送参数,并等待UI初始化完成后执行跳转逻辑,具体步骤如下:
1. 在App启动时提取推送参数
应用被杀死后点击推送启动,userNotificationCenter:didReceiveResponse:不会触发,必须在didFinishLaunchingWithOptions中提取推送的userInfo:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 常规初始化代码(FCM、UNUserNotificationCenter配置等) // 处理杀死状态下的推送启动 if let remoteNotification = launchOptions?[.remoteNotification] as? [AnyHashable: Any] { // 延迟执行跳转,确保Tab Bar和导航控制器已完成初始化 DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { NotificationHandler.shared.handleNotification(remoteNotification) } } return true }
2. 适配Tab Bar的跳转逻辑
修改你的导航工具类,确保能正确获取Tab Bar控制器及对应Tab的导航栈,避免因UI未初始化导致的跳转失败:
class PushnotificationNavigation { static let shared = PushnotificationNavigation() func chapterDetailNavigation(model: PushNotificationModel) { // iOS 13+ 正确获取根窗口与Tab Bar控制器 guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let window = scene.windows.first, let tabBarController = window.rootViewController as? UITabBarController else { return } // 切换到目标Tab(示例为Tab A,索引0) tabBarController.selectedIndex = 0 // 获取当前Tab的导航控制器 guard let navController = tabBarController.selectedViewController as? UINavigationController else { return } // 创建目标页面并跳转 let detailVC = ChapterDetailViewController(model: model) // 替换为你的目标VC navController.pushViewController(detailVC, animated: true) } }
3. 保留原有后台/前台状态的处理逻辑
不要删除userNotificationCenter:didReceiveResponse:中的代码,该方法仍负责处理后台/前台状态下的推送跳转:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo NotificationHandler.shared.handleNotification(userInfo) completionHandler() }
关键注意事项
- 跳转时机:必须延迟执行跳转逻辑,确保Tab Bar、导航控制器等UI组件已完成初始化,否则会出现获取不到控制器的情况
- iOS版本适配:iOS 13+需通过
UIWindowScene获取窗口,不能直接使用keyWindow - 推送payload校验:确保推送的
userInfo中包含type和payload字段,且格式符合解析要求 - 测试验证:测试时必须完全杀死App(从多任务界面划掉),再点击推送通知验证跳转效果
内容的提问来源于stack exchange,提问作者Sushil Dhital
相关产品推荐
相关产品推荐

