Flutter开发iOS+WatchOS应用:FCM通知点击无法读取数据求助
解决WatchOS点击FCM通知无法读取自定义数据的问题
核心问题分析
当iPhone关机时,FCM通知直接推送到Apple Watch,此时需要确保通知Payload符合APNs规范,同时WatchOS Extension的通知处理逻辑能正确提取并传递数据到Flutter层。
具体解决方案
1. 规范FCM通知的Payload格式
FCM推送给Watch的通知,自定义数据必须放在aps字段的同级,不能嵌套在aps内部,否则会被APNs过滤。示例Payload如下:
{ "apns": { "payload": { "aps": { "alert": { "title": "新消息提醒", "body": "您有一条未读消息" }, "sound": "default" }, "customData": { "messageId": "msg_12345", "sender": "小明", "content": "今晚一起吃饭?" } } }, "token": "WATCH_DEVICE_REGISTRATION_TOKEN" }
2. 修正WatchOS Extension的通知处理代码
在你的AppDelegate中,需要确保点击通知时能正确提取数据,并通过MethodChannel直接传递给Flutter层:
class AppDelegate: NSObject, WKExtensionDelegate, UNUserNotificationCenterDelegate { func handleUserActivity(_ userInfo: [AnyHashable : Any]?) { guard let userInfo = userInfo else { return } print("[notification] handleUserActivity: \(userInfo)") passDataToFlutter(from: userInfo) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("[notification] 通知被点击打开") let userInfo = response.notification.request.content.userInfo print("[notification] 通知数据: \(userInfo)") passDataToFlutter(from: userInfo) completionHandler() } // 提取自定义数据并通过MethodChannel传递给Flutter private func passDataToFlutter(from userInfo: [AnyHashable: Any]) { guard let customData = userInfo["customData"] as? [String: Any], let engine = WKExtension.shared().rootInterfaceController?.flutterEngine else { return } let channel = FlutterMethodChannel(name: "com.your.app/notification", binaryMessenger: engine.binaryMessenger) channel.invokeMethod("updateNotificationUI", arguments: customData) } // 其他原有方法保持不变... }
3. Flutter层接收数据并更新UI
在WatchOS的Flutter代码中,通过MethodChannel监听原生传递的数据,触发UI更新:
import 'package:flutter/services.dart'; class WatchNotificationManager { static const _notificationChannel = MethodChannel('com.your.app/notification'); static Map<String, dynamic>? currentNotificationData; static Future<void> init() async { _notificationChannel.setMethodCallHandler((call) async { if (call.method == 'updateNotificationUI') { currentNotificationData = Map<String, dynamic>.from(call.arguments); // 触发UI更新,比如调用setState或者通知状态管理工具 // 示例: // if (mounted) setState(() {}); // 或者使用Provider/BloC等通知UI刷新 } }); } }
4. 检查WatchOS Extension配置
- 在Extension的
Info.plist中添加后台权限:<key>UIBackgroundModes</key> <array> <string>remote-notification</string> </array> - 确认Extension已配置正确的APNs证书,且FCM已成功获取Watch的设备令牌。
5. 调试建议
- 在所有通知处理方法中打印完整的
userInfo,确认自定义数据是否存在; - 使用Xcode的
Notification Simulator模拟推送,验证Payload解析是否正常; - 检查WatchOS的通知设置,确保应用允许接收通知。
内容的提问来源于stack exchange,提问作者MedCh
相关产品推荐
相关产品推荐

