首页 > 解决方案 > 关闭应用程序后 Xamarin.IOS UILocalNotification.UserInfo 为空

问题描述

打开应用程序时,本地通知会正常工作。但有些情况下,本地通知在关闭应用程序后仍保留在通知中心。然后单击通知启动应用程序,通知数据应在AppDelegate.FinishedLaunching方法中的选项中传递。Options 包含键UIApplicationLaunchOptionsLocalNotificationKey,其值为UIKit.UILocalNotification类型。此值包含应填充通知数据的 UserInfo 属性。但是这个 UserInfo 是空的。

另一个问题是当本地通知保留在通知中心并且应用程序重新启动时。单击通知会导致应用程序再次启动并立即停止。

你有过这样的问题吗?Xamarin 有问题吗?如何处理这样的场景?

创建通知:

public void DisplayNotification(MessageInfo info)
{
    var notificationCenter = UNUserNotificationCenter.Current;

    var content = new UNMutableNotificationContent();
    content.Title = info.Title;
    content.Body = info.Body;
    content.UserInfo = IosStaticMethods.CreateNsDictFromMessageInfo(info);

    UNNotificationTrigger trigger;
    trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false);
    var id = (++_LastNotificationId).ToString();
    var request = UNNotificationRequest.FromIdentifier(id, content, trigger);

    notificationCenter.Delegate = new UserNotificationCenterDelegate();

    notificationCenter.AddNotificationRequest(request, (error) =>
    {
        //handle error
    });
}

internal class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
{
    public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
    {
        completionHandler(UNNotificationPresentationOptions.Alert);
    }

    public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
    {
        //do something
    }
}

在 AppDelegate.FinishedLaunching 中处理通知

if (options != null)
{
    var notification = options["UIApplicationLaunchOptionsLocalNotificationKey"] as UIKit.UILocalNotification;
    var userInfo = notification.UserInfo;//the userInfo is null
}

标签: xamarinxamarin.iosnotifications

解决方案


似乎 NSDictionary 不应该包含 NSNull 值。删除 NSNull 值后一切正常,即使 NSDictionary 文档https://developer.apple.com/documentation/foundation/nsdictionary说 NSNull 是允许的。


推荐阅读