共用方式為


Xamarin.iOS 中的群組通知

根據預設,iOS 12 會將應用程式的所有通知放在群組中。 鎖定畫面和通知中心會將此群組顯示為堆疊,上面有最新的通知。 用戶可以展開群組,以查看其包含的所有通知,並關閉整個群組。

應用程式也可以依線程分組通知,讓使用者更輕鬆地尋找並與其感興趣的特定信息互動。

要求授權並允許前景通知

應用程式必須先要求許可權才能傳送本機通知。 在範例應用程式的 AppDelegate中, FinishedLaunching 方法會要求此許可權:

public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
    UNUserNotificationCenter center = UNUserNotificationCenter.Current;
    center.RequestAuthorization(UNAuthorizationOptions.Alert, (bool success, NSError error) =>
    {
        // Set the Delegate regardless of success; users can modify their notification
        // preferences at any time in the Settings app.
        center.Delegate = this;
    });
    return true;
}

Delegate (如上設定) UNUserNotificationCenter 決定前景應用程式是否應該藉由呼叫傳遞至 WillPresentNotification的完成處理程式來顯示傳入通知:

[Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, System.Action<UNNotificationPresentationOptions> completionHandler)
{
    completionHandler(UNNotificationPresentationOptions.Alert);
}

參數 UNNotificationPresentationOptions.Alert 指出應用程式應該顯示警示,但不應該播放音效或更新徽章。

線程通知

重複點選範例應用程式的 [訊息與 Alice] 按鈕,讓它傳送與名為 Alice 之朋友交談的通知。 由於此交談的通知是相同線程的一部分,鎖定畫面和通知中心會將它們分組在一起。

若要開始與不同朋友的交談,請點選 [ 選擇新朋友 ] 按鈕。 此交談的通知會出現在不同的群組中。

ThreadIdentifier

每當範例應用程式啟動新的線程時,就會建立唯一的線程標識碼:

void StartNewThread()
{
    threadId = $"message-{friend}";
    // ...
}

若要傳送線程通知,範例應用程式:

async partial void ScheduleThreadedNotification(UIButton sender)
{
    var center = UNUserNotificationCenter.Current;

    UNNotificationSettings settings = await center.GetNotificationSettingsAsync();
    if (settings.AuthorizationStatus != UNAuthorizationStatus.Authorized)
    {
        return;
    }

    string author =  // ...
    string message = // ...

    var content = new UNMutableNotificationContent()
    {
        ThreadIdentifier = threadId,
        Title = author,
        Body = message,
        SummaryArgument = author
    };

    var request = UNNotificationRequest.FromIdentifier(
        Guid.NewGuid().ToString(),
        content,
        UNTimeIntervalNotificationTrigger.CreateTrigger(1, false)
    );

    center.AddNotificationRequest(request, null);

    // ...
}

來自相同應用程式且具有相同線程標識碼的所有通知都會出現在相同的通知群組中。

注意

若要在遠端通知上設定線程標識碼,請將密鑰新增 thread-id 至通知的 JSON 承載。 如需詳細資訊,請參閱Apple的 產生遠端通知 檔。

SummaryArgument

SummaryArgument 會指定通知將如何影響通知所屬通知群組左下角顯示的摘要文字。 iOS 會從相同群組中的通知匯總摘要文字,以建立整體摘要描述。

範例應用程式會使用訊息的作者作為摘要自變數。 使用此方法時,使用 Alice 的六個通知群組摘要文字可能會是 Alice 和 Me 的 5 個通知。

未線程通知

每個點選範例應用程式的 [約會提醒 ] 按鈕都會傳送其中一個各種約會提醒通知。 由於這些提醒不會進行線程處理,因此它們會出現在鎖定畫面和通知中心的應用層級通知群組中。

為了傳送未線程的通知,範例應用程式的 ScheduleUnthreadedNotification 方法會使用與上述類似的程序代碼。 不過,它不會在 物件上UNMutableNotificationContent設定 ThreadIdentifier