iOS后台didReceiveRemoteNotification未触发问题(Firebase+Postman)
问题:
didReceiveRemoteNotification未被调用 应用在后台时可正常收到通知(真实设备测试),期望后台收到通知且无用户交互(未点击通知)时自动触发该方法。设备系统为iOS 16.3,使用Xcode 14.1开发。
已执行操作
使用Firebase服务器,通过Postman发送推送请求:
- 请求头:已添加
apns-push-type、apns-priority、apns-topic(参考Apple官方推送文档配置) - 请求体:尝试将
content-available设为true、"true"和1,请求体结构如下:
{ "aps" : { "content-available" : 1 }, "to":"my fcm token", "notification" : { "title" : "Alarm", "body" : "Testing" } }
- 应用配置:已执行
FirebaseApp.configure()、设置Messaging.messaging().delegate = self、UIApplication.shared.registerForRemoteNotifications()、Messaging.messaging().apnsToken = deviceToken;已开启Push Notifications和Background Modes中的Remote notifications、Background fetch选项。
解决方案
- 修正FCM推送请求结构
FCM发送静默推送(后台触发回调)时,不能同时包含notification字段——这个字段会触发通知弹窗,而静默推送需要用data字段传递自定义内容,且aps里的content-available必须设为1。正确请求体示例:
{ "to": "my fcm token", "data": { "title": "Alarm", "body": "Testing" }, "aps": { "content-available": 1 } }
同时请求头要把apns-push-type设为background,apns-priority设为5(后台推送必须用低优先级,否则易被系统拦截)。
确认回调方法的正确实现
必须实现带fetchCompletionHandler的版本:func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // 处理推送内容 completionHandler(.newData) // 必须调用这个告知系统任务状态 }如果你用SwiftUI,要通过
@UIApplicationDelegateAdaptor关联自定义Delegate类,确保上述方法被正确挂载。验证后台模式配置
除了Xcode界面开启Background Modes,还要确认Info.plist中存在UIBackgroundModes数组并包含remote-notification项:
<key>UIBackgroundModes</key> <array> <string>remote-notification</string> <string>fetch</string> </array>
- 测试注意事项
- 测试时让应用真正处于后台(手动切到桌面,不要在Xcode调试时挂起);
- 避免短时间内频繁发测试推送,iOS会对后台推送节流,建议间隔1分钟以上;
- 确认FCM Token有效,可通过
Messaging.messaging().token获取当前token核对。
内容的提问来源于stack exchange,提问作者Joey
相关产品推荐
相关产品推荐

