Разрешение на уведомление должно быть запрошено, как только приложение запустится, добавив следующий код к методу FinishedLaunching
AppDelegate
и установив желаемый тип уведомления (UNAuthorizationOptions
):
...
using UserNotifications;
...
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
....
//after iOS 10
if(UIDevice.CurrentDevice.CheckSystemVersion(10,0))
{
UNUserNotificationCenter center = UNUserNotificationCenter.Current;
center.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.UNAuthorizationOptions.Badge, (bool arg1, NSError arg2) =>
{
});
center.Delegate = new NotificationDelegate();
}
else if(UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert| UIUserNotificationType.Badge| UIUserNotificationType.Sound,new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
return true;
}
Новое в iOS 10, приложение может по-разному обрабатывать уведомления, когда оно находится на переднем плане и запускается уведомление. Предоставляя UNUserNotificationCenterDelegate
и внедряя UserNotificationCentermethod
, приложение может взять на себя ответственность за отображение Уведомления. Например:
using System;
using ObjCRuntime;
using UserNotifications;
namespace workplat
{
public class NotificationDelegate:UNUserNotificationCenterDelegate
{
public NotificationDelegate()
{
}
public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
// Do something with the notification
Console.WriteLine("Active Notification: {0}", notification);
// Tell system to display the notification anyway or use
// `None` to say we have handled the display locally.
completionHandler(UNNotificationPresentationOptions.Alert|UNNotificationPresentationOptions.Sound);
}
public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
// Take action based on Action ID
switch (response.ActionIdentifier)
{
case "reply":
// Do something
break;
default:
// Take action based on identifier
if (response.IsDefaultAction)
{
// Handle default action...
}
else if (response.IsDismissAction)
{
// Handle dismiss action
}
break;
}
// Inform caller it has been handled
completionHandler();
}
}
}
Чтобы создать и зарегистрировать пользовательское действие в системе, используйте следующий код:
public void RegisterNotification(long time)
{
UNUserNotificationCenter center = UNUserNotificationCenter.Current;
//creat a UNMutableNotificationContent which contains your notification content
UNMutableNotificationContent notificationContent = new UNMutableNotificationContent();
notificationContent.Title = "xxx";
notificationContent.Body= "xxxx";
notificationContent.Sound = UNNotificationSound.Default;
UNTimeIntervalNotificationTrigger trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(time, false);
UNNotificationRequest request = UNNotificationRequest.FromIdentifier("FiveSecond", notificationContent, trigger);
center.AddNotificationRequest(request,(NSError obj) =>
{
});
}
При вызове этого метода для emample:
RegisterNotification(20);//set the time you want to push notification
Уведомление будет отправлено через 20 секунд, если вы закроете свое приложение.
Я загрузил демо на свой github, вы можете скачать его для справки: Демонстрационная ссылка .
И вы можете получить доступ к ссылке для получения дополнительной информации: Документ MicroSoft