本地通知在应用程序打开时应该正常工作。但有些情况下,在关闭申请后本地通知仍留在通知中心。然后单击通知启动应用程序,并在AppDelegate.FinishedLaunching方法中的选项中传递通知数据。选项包含UIApplicationLaunchOptionsLocalNotificationKey键,其值为UIKit.UILocalNotification。此值包含UserInfo属性,该属性应填充通知数据。但是这个UserInfo是null。
另一个问题是当本地通知仍在通知中心并且应用程序重新启动时。单击通知会导致应用程序再次启动并立即停止。
你有这样的问题吗? 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
}
似乎NSDictionary不应包含NSNull值。删除NSNull值后,即使NSDictionary文档https://developer.apple.com/documentation/foundation/nsdictionary表示允许NSNull,一切都可以。