You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 01:23:11