CarPlay推送通知点击后无法触发didReceive方法及展示Alert模板问题求助
我之前折腾CarPlay推送的时候也碰到过一模一样的问题,手机端点击通知顺顺利利触发回调,一到CarPlay上就没反应,当时卡了好半天!结合我踩过的坑,给你几个可行的排查和解决方向:
别死盯着AppDelegate的
didReceiveRemoteNotification了!CarPlay场景有自己的回调逻辑
从iOS 13引入多Scene架构后,CarPlay是独立的CPTemplateApplicationScene,手机端的通知点击会走AppDelegate或者主Scene的回调,但CarPlay的通知点击触发的是CarPlay场景的生命周期方法。你需要在SceneDelegate里的scene(_:willConnectTo:options:)方法里检查启动参数:func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // 检查是否是通过点击CarPlay通知启动的场景 if let notificationResponse = connectionOptions.notificationResponse { // 这里处理通知点击逻辑,替代AppDelegate的didReceive processCarPlayNotification(response: notificationResponse) } // 其他CarPlay场景初始化代码 } private func processCarPlayNotification(response: UNNotificationResponse) { let notificationContent = response.notification.request.content // 解析通知内容,比如标题、正文 let alertTemplate = CPAlertTemplate( title: notificationContent.title, message: notificationContent.body ) // 获取CarPlay的界面控制器,推送Alert模板 guard let carPlayScene = scene as? CPTemplateApplicationScene, let interfaceController = carPlayScene.interfaceController else { return } interfaceController.pushTemplate(alertTemplate, animated: true) }在SceneDelegate中实现专属的通知接收方法
如果CarPlay场景已经处于活跃状态,点击通知可能会触发scene(_:didReceiveRemoteNotification:fetchCompletionHandler:),所以别忘了在SceneDelegate里也实现这个方法:func scene(_ scene: UIScene, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { let title = userInfo["aps"]?["alert"]?["title"] as? String ?? "新通知" let message = userInfo["aps"]?["alert"]?["body"] as? String ?? "" showCarPlayAlert(title: title, message: message) completionHandler(.newData) } private func showCarPlayAlert(title: String, message: String) { guard let carPlayScene = scene as? CPTemplateApplicationScene, let interfaceController = carPlayScene.interfaceController else { return } let alert = CPAlertTemplate(title: title, message: message) interfaceController.pushTemplate(alert, animated: true) }确认通知配置和CarPlay的关联
要确保你的推送payload里的category和你在UNNotificationCenter注册的通知类别对应,而且这个类别要支持CarPlay的交互。比如注册通知类别时:let carPlayNotificationCategory = UNNotificationCategory( identifier: "carplay_alert_category", actions: [], intentIdentifiers: [], options: [.customDismissAction] ) UNUserNotificationCenter.current().setNotificationCategories([carPlayNotificationCategory])推送payload里的
aps字段要包含"category": "carplay_alert_category",这样系统才知道这个通知要触发CarPlay的对应交互。检查Info.plist的CarPlay配置
确认你的Info.plist里已经正确配置了CPTemplateApplicationSceneManifest,并且ApplicationCategory设置为com.apple.carplay.driving-tasks,和你的entitlement一致,不然CarPlay场景可能无法正常接收通知事件。
内容来源于stack exchange

