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

时间:2017-03-10 12:32:05

标签: xamarin xamarin.ios xamarin.forms uilocalnotification

我想向用户显示通知,但title始终为null。问题是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/

1 个答案:

答案 0 :(得分:2)

Xamarin似乎有一个错误。我尝试了你的代码,事实上,无论你设置什么,AlertAction总是为null,但只有在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用于Action文本,以防您想从通知中设置一个。

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

但正如你现在正在使用" Ok"在真正的问题得到解决之前,你不应该有任何问题。

希望这有帮助!