Xamarin IOS - UserInfo 自定义数据字典始终为空

Xamarin IOS - UserInfo custom data dictionary is always empty

下面的方法展示了我如何创建通知。我在 UserInfo 词典中添加了一个新项目。

private UNNotificationRequest CreateNotification(Geofence geofence)
{
        var content = new UNMutableNotificationContent();
        content.Title = "title";
        content.Subtitle = "subtitle";
        content.Body = "This is the message body of the notification.";
        content.Badge = 2;

        content.UserInfo.Append(new KeyValuePair<NSObject, NSObject>((NSString)"id", (NSString)"bla"));

        var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);

        var request = UNNotificationRequest.FromIdentifier("test1", content, trigger);
        return request;
}

问题如下:

public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
    foreach (var item in response.Notification.Request.Content.UserInfo)
    {
    }

    // Inform caller it has been handled
    completionHandler();
}

UserInfo 字典总是空的。为什么会这样,我该如何解决?

你需要在switch语句中获取逻辑

public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
    {   
        // Take action based on Action ID
        switch (response.ActionIdentifier)
        {
            case "reply":
                // Do something
                break;
            default:
                // Take action based on identifier
                if (response.IsDefaultAction)
                {
                    // Handle default action...
                    var item = response.Notification.Request.Content.UserInfo;
                }
                else if (response.IsDismissAction)
                {
                    // Handle dismiss action
                }
                break;
        }

        // Inform caller it has been handled
        completionHandler();
    }

更新

看来您添加 UserInfo 的方式有误。检查以下代码

content.UserInfo = NSDictionary.FromObjectAndKey(new KeyValuePair<NSObject, NSObject>((NSString)"id", (NSString)"bla"));