Xamarin 中的本地通知 AlertAction 始终为 null iOS

Local notification AlertAction always null in Xamarin iOS

我想向用户显示通知,但标题始终为空。问题是 notification.AlertAction 在显示通知之前为空。

    public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification)
    {
        // notification.AlertAction is null!!! while notification.AlertBody is correct
        UIAlertController okayAlertController = UIAlertController.Create(notification.AlertAction, notification.AlertBody, UIAlertControllerStyle.Alert);
        okayAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

        Window.RootViewController.PresentViewController(okayAlertController, true, null);

        UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
    }

我正在设置 notification.AlertAction 和 notification.AlertBody:

public class NotificationService_iOS : INotificationService
{
    public void Notify(string title, string text)
    {
        var notification = new UILocalNotification();
        notification.FireDate = NSDate.FromTimeIntervalSinceNow(0);
        notification.AlertAction = title;
        notification.AlertBody = text;
        notification.ApplicationIconBadgeNumber = 1;
        notification.SoundName = UILocalNotification.DefaultSoundName;
        UIApplication.SharedApplication.ScheduleLocalNotification(notification);
    }
}

我正在学习本教程:https://developer.xamarin.com/guides/ios/application_fundamentals/notifications/local_notifications_in_ios_walkthrough/

这部分在 Xamarin 中似乎存在错误。我试过你的代码,实际上 AlertAction 总是空的,不管你设置什么,但这只有在 运行 设备上的代码 iOS 10+ 时才会发生。 运行 使用 iOS 9.3 的模拟器中的相同代码和一切 运行 都很好。

一直在查看 Xamarin.iOS 代码,但无法解决任何奇怪的问题,因此下一步将打开一个问题。

一件事:对于您的具体示例,您可以使用 AlertTitle

public void Notify(string title, string text)
{
    var notification = new UILocalNotification();
    notification.FireDate = NSDate.FromTimeIntervalSinceNow(0);
    notification.AlertTitle = title;
    notification.AlertBody = text;
     // Use this if you want to set the Action Text from here.
    notification.AlertAction = "Got it!!";
    notification.ApplicationIconBadgeNumber = 1;
    notification.SoundName = UILocalNotification.DefaultSoundName;
    UIApplication.SharedApplication.ScheduleLocalNotification(notification);
}

UIAlertController okayAlertController = UIAlertController.Create(notification.AlertTitle, notification.AlertBody, UIAlertControllerStyle.Alert);

这实际上是 属性 设置您想要的通知标题。如果您想从通知中设置一个,AlertAction 用于操作文本。

okayAlertController.AddAction(UIAlertAction.Create(notification.AlertAction, UIAlertActionStyle.Default, null));

但由于您目前只使用 "Ok",在真正的问题得到解决之前,您应该不会遇到任何问题。

希望对您有所帮助!