Swift推送通知回调application(_:didReceiveRemoteNotification:fetchCompletionHandler:)不触发怎么办
回调无法触发的常见原因
- 推送 payload 结构不符合要求:如果是触发该回调的静默推送,payload 必须包含
content-available: 1字段,若同时携带alert、sound、badge等前台通知字段,会被系统判定为普通通知,不会走该后台回调 - 推送请求参数错误:APNs 请求的
apns-priority字段不能设为10,静默推送必须设为5,否则推送会被APNs服务直接拦截 - 系统版本适配问题:iOS 10+ 集成
UserNotifications框架后,前台收到通知默认会走UNUserNotificationCenterDelegate的相关回调,不会触发该UIApplication的旧版回调 - 重复实现同功能回调:如果项目中同时实现了不带
fetchCompletionHandler参数的旧版didReceiveRemoteNotification方法,系统会优先调用无回调参数的方法,导致当前回调不触发 - 后台权限被限制:用户手动关闭了APP的后台刷新权限,或者设备处于低电量模式时,静默推送会被系统拦截,不会触发回调
- 进程被手动杀死:用户上滑杀掉APP进程后,静默推送无法唤醒APP,该回调不会被触发,只有用户主动打开APP或点击普通通知启动APP才会接收通知信息
- 证书与环境不匹配:推送证书未开启推送能力,或者服务端使用的推送证书/环境(开发/生产)和APP运行的环境不匹配,设备根本无法收到推送
- Bundle ID 不匹配:Xcode运行的Bundle ID和推送证书绑定的Bundle ID不一致,无法完成推送注册,自然不会触发回调
必须完成的前置配置
- 开启项目相关能力:在Xcode的
Signing & Capabilities标签页添加Push Notifications能力,同时添加Background Modes能力,勾选Remote notifications选项 - 申请通知权限并注册推送:App启动时主动申请通知权限,用户同意后注册远程推送,示例代码如下:
import UserNotifications // 在didFinishLaunchingWithOptions中调用 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in if granted { DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } }
- 实现DeviceToken接收回调:必须实现
didRegisterForRemoteNotificationsWithDeviceToken方法,拿到设备token后上传至你的推送服务端,否则服务端无法定向给当前设备发送推送
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // 将deviceToken转为字符串后上传给服务端 let tokenStr = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() print("设备推送token: \(tokenStr)") }
- 适配iOS 10+的通知回调:如果需要兼容iOS 10及以上系统,建议同时实现
UNUserNotificationCenterDelegate的回调,覆盖前台接收通知、点击通知启动APP的场景:
// 前台收到通知时触发 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { return [.banner, .sound] } // 点击通知打开APP时触发 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async { let userInfo = response.notification.request.content.userInfo // 处理通知逻辑 }
- 校验推送payload格式:静默推送的payload必须符合以下规范示例:
{ "aps": { "content-available": 1 }, "your_custom_key": "your_custom_value" }
内容的提问来源于stack exchange,提问作者Punreach Rany
相关产品推荐
相关产品推荐

