.NET MAUI 7中如何解析iOS推送通知JSON Payload?
关于UNNotification中推送负载的解析问题
推送负载确实是UNNotification对象的一部分,它藏在notification.Request.Content.UserInfo属性里,这个属性对应APNs推送的完整JSON负载(包括标准字段和自定义数据)。
解析步骤(Xamarin.iOS/C#环境)
- 从
UNNotification对象获取请求实例:通过notification.Request拿到UNNotificationRequest - 提取负载内容:访问
request.Content.UserInfo,这是NSDictionary类型,直接对应推送的JSON结构 - 解析数据:可以直接通过键名取值,或者转换成C#的
Dictionary<string, object>方便操作
示例代码(整合解析逻辑)
public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler) { // 解析推送负载 var notificationRequest = notification.Request; var payloadDict = notificationRequest.Content.UserInfo; // 方式1:直接读取自定义字段(比如"custom_data") if (payloadDict.ContainsKey(new NSString("custom_data"))) { var customData = payloadDict[new NSString("custom_data")].ToString(); // 这里处理自定义数据逻辑 } // 方式2:转换为C# Dictionary,统一处理标准字段和自定义字段 var payloadDictionary = NSDictionary<NSString, NSObject>.FromDictionary(payloadDict) .ToDictionary(k => k.Key.ToString(), v => v.Value); // 解析标准aps字段 if (payloadDictionary.TryGetValue("aps", out var apsObj)) { var apsDict = apsObj as Dictionary<string, object>; if (apsDict?.TryGetValue("alert", out var alertObj) == true) { var alertDict = alertObj as Dictionary<string, object>; var title = alertDict?["title"]?.ToString(); var body = alertDict?["body"]?.ToString(); // 处理标题、内容等信息 } } // 原有通知展示逻辑 if (UIDevice.CurrentDevice.CheckSystemVersion(14, 0)) { completionHandler(UNNotificationPresentationOptions.List | UNNotificationPresentationOptions.Banner | UNNotificationPresentationOptions.Sound); } else { completionHandler(UNNotificationPresentationOptions.Alert | UNNotificationPresentationOptions.Sound); } }
补充说明
UserInfo包含APNs标准的aps字段(如alert、badge、sound),以及所有你自定义的额外字段- Xamarin环境下,
NSDictionary可以通过ToDictionary()方法转换成C#原生字典,简化数据操作 - 注意键名要和推送负载里的键完全匹配,区分大小写
内容的提问来源于stack exchange,提问作者Cef
相关产品推荐
相关产品推荐

