共用方式為


Xamarin.iOS 中的通知管理

在 iOS 12 中,操作系統可以從通知中心和 設定 應用程式深層連結至應用程式的通知管理畫面。 此畫面應該允許使用者選擇加入和退出應用程式傳送的各種通知類型。

通知管理畫面

在範例應用程式中, ManageNotificationsViewController 定義使用者介面,讓用戶能夠獨立啟用和停用紅色通知和綠色通知。 這是標準 UIViewControllerUISwitch包含每個通知型態的 。 切換任一類型通知的切換會儲存在使用者預設值中,使用者對該類型的通知喜好設定:

partial void HandleRedNotificationsSwitchValueChange(UISwitch sender)
{
    NSUserDefaults.StandardUserDefaults.SetBool(sender.On, RedNotificationsEnabledKey);
}

注意

通知管理畫面也會檢查使用者是否已完全停用應用程式的通知。 如果是,它會隱藏個別通知類型的切換。 若要這樣做,通知管理畫面:

傳送通知的 ViewController 範例應用程式類別會先檢查使用者的喜好設定,再傳送本機通知,以確保通知是用戶實際想要接收的類型:

partial void HandleTapRedNotificationButton(UIButton sender)
{
    bool redEnabled = NSUserDefaults.StandardUserDefaults.BoolForKey(ManageNotificationsViewController.RedNotificationsEnabledKey);
    if (redEnabled)
    {
        // ...

iOS 深層連結至通知中心的通知管理畫面,以及應用程式在 設定 應用程式中的通知設定。 為了方便進行這項作業,應用程式必須:

  • 表示通知管理畫面可透過傳遞 UNAuthorizationOptions.ProvidesAppNotificationSettings 至應用程式的通知授權要求來使用。
  • IUNUserNotificationCenterDelegate實作 OpenSettings 方法。

授權要求

若要向操作系統指出通知管理畫面可供使用,應用程式應該將選項(以及它所需的任何其他通知傳遞選項)RequestAuthorization傳遞給 UNAuthorizationOptions.ProvidesAppNotificationSettings 上的UNUserNotificationCenter方法。

例如,在範例應用程式的 AppDelegate中:

public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
    // Request authorization to send notifications
    UNUserNotificationCenter center = UNUserNotificationCenter.Current;
    var options = UNAuthorizationOptions.ProvidesAppNotificationSettings | UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Provisional;
    center.RequestAuthorization(options, (bool success, NSError error) =>
    {
        // ...

Open 設定 方法

OpenSettings由系統呼叫以深層連結至應用程式通知管理畫面的方法,應該將使用者直接巡覽至該畫面。

在範例應用程式中,這個方法會視需要對 執行 segue ManageNotificationsViewController

[Export("userNotificationCenter:openSettingsForNotification:")]
public void OpenSettings(UNUserNotificationCenter center, UNNotification notification)
{
    var navigationController = Window.RootViewController as UINavigationController;
    if (navigationController != null)
    {
        var currentViewController = navigationController.VisibleViewController;
        if (currentViewController is ViewController)
        {
            currentViewController.PerformSegue(ManageNotificationsViewController.ShowManageNotificationsSegue, this);
        }

    }
}