Sus*_*ver 5

使用an时UNUserNotificationCenterDelegate,请确保在WillFinishLaunchingFinishedLaunching应用程序的方法中进行分配UIApplicationDelegate

您必须在应用程序完成启动之前立即将委托对象分配给UNUserNotificationCenter对象。

参考:UNUserNotificationCenterDelegate

AppDelegate.cs示例

public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
    UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) =>
    {
        // Handle the user approval or refusal of your notifications...
    });
    UNUserNotificationCenter.Current.Delegate = new MyUNUserNotificationCenterDelegate();
    return true;
}
Run Code Online (Sandbox Code Playgroud)

在该示例中,我正在创建/分配一个名为的委托类MyUNUserNotificationCenterDelegate,因此您需要实现该类。

MyUNUserNotificationCenterDelegate类示例:

UNUserNotificationCenterDelegate示例将捕获发送的每个本地通知,并在在锁定屏幕上显示该通知或将详细信息输出到syslog之间切换。

public class MyUNUserNotificationCenterDelegate : UNUserNotificationCenterDelegate
{
    bool toggle;
    public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
    {
        if (toggle)
            completionHandler(UNNotificationPresentationOptions.Alert);
        else
        {
            Console.WriteLine(notification);
            completionHandler(UNNotificationPresentationOptions.None);
        }
        toggle = !toggle;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您实际上将需要发送一些通知,这将设置一个简单的重复通知:

创建/安排本地通知:

// Schedule a repeating Notification...
var content = new UNMutableNotificationContent();
content.Title = new NSString("From SushiHangover");
content.Body = new NSString("StackOverflow rocks");
content.Sound = UNNotificationSound.Default;
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(timeInterval: 60, repeats: true);
var request = UNNotificationRequest.FromIdentifier(identifier: "FiveSecond", content: content, trigger: trigger);
UNUserNotificationCenter.Current.AddNotificationRequest(request, (NSError error) =>
{
    if (error != null) Console.WriteLine(error);
});
Run Code Online (Sandbox Code Playgroud)

每隔60秒就会发送一次通知,如果您处于锁定屏幕,则每120秒将收到一次警报...

在此处输入图片说明

推荐阅读以了解Xamarin.iOS / C#如何与委托,协议和事件进行交互:

iOS使用Objective-C委托来实现委托模式,其中一个对象将工作传递给另一对象。工作的对象是第一个对象的委托。对象在发生某些事情后通过向其发送消息来告诉其委托人进行工作。在Objective-C中发送这样的消息在功能上等同于在C#中调用方法。委托响应这些调用实现方法,从而为应用程序提供功能。

参考:Xamarin.iOS和代表