Flutter iOS端Firebase Cloud Messaging无法接收静默数据消息
Firebase Cloud Messaging (Flutter):启用Method Swizzling时无法接收Data Messages
问题描述
- 应用在前台、后台及被杀状态下均无法接收data messages
- Notification Messages可正常接收
- 启用Method Swizzling时,data messages无法触发任何FCM消息监听器
- 禁用Method Swizzling(在
info.plist中设置<key>FirebaseAppDelegateProxyEnabled</key><false/>)后,应用可接收data messages,但Firebase明确表示Flutter开发者不应禁用该功能
已完成配置
- 在Firebase控制台配置APNs Authentication Key
- 在Xcode中添加Push Notifications能力
- 启用Background Fetch和Remote Notifications后台模式
测试用FCM Payload
{ "message": { "token": "{FCM_TOKEN_HERE}", "data": { "type": "TEST" }, "apns": { "payload": { "aps": { "content-available": 1 } }, "headers": { "apns-priority": "5" } } } }
环境信息
- Firebase Messaging版本:14.8.1
- 开发框架:Flutter
解决方案
1. 规范实现FCM消息监听器
启用Method Swizzling时,必须严格按照Flutter FCM要求注册监听器:
- 前台消息监听:使用
FirebaseMessaging.onMessage.listen处理 - 后台/被杀状态消息:必须实现顶级函数形式的
FirebaseMessaging.onBackgroundMessage回调(不能是类方法或闭包),示例代码:
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async { await Firebase.initializeApp(); // 处理data消息逻辑 print("收到后台data消息: ${message.data}"); } void main() { FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); runApp(MyApp()); }
2. 修正APNs Payload配置
确保payload符合纯data消息的要求:
aps字典仅保留content-available: 1,不要添加alert、badge、sound等字段(否则会被识别为notification消息)- 确认APNs Authentication Key的bundle ID与应用完全匹配,且已开启推送权限
3. 避免覆盖Firebase的Swizzled方法
如果自定义了App Delegate方法,需手动调用Firebase的消息处理逻辑,以Swift为例:
import FirebaseMessaging func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { Messaging.messaging().appDidReceiveMessage(userInfo) completionHandler(.newData) }
不要自行实现application:didReceiveRemoteNotification:等方法,否则会覆盖Firebase的Swizzled逻辑。
4. 升级Firebase Messaging版本
当前使用的14.8.1版本存在已知的Method Swizzling与data消息兼容问题,建议升级到最新稳定版,执行命令:
flutter pub upgrade firebase_messaging
5. 验证Xcode后台模式配置
在Xcode的Signing & Capabilities中,确认Background Modes下的Remote notifications和Background fetch已勾选,且Info.plist中UIBackgroundModes数组包含remote-notification和fetch字段。
内容的提问来源于stack exchange,提问作者Bob-Touchwonders
相关产品推荐
相关产品推荐

