Xamarin 中的分组通知Grouped notifications in Xamarin.iOS

默认情况下,iOS 12 将所有应用的通知放置在一个组中。By default, iOS 12 places all of an app's notifications in a group. 锁定屏幕和通知中心将此组显示为最顶部有最新通知的堆栈。The lock screen and Notification Center display this group as a stack with the most recent notification on top. 用户可以展开组以查看它包含的所有通知,并将整个组关闭。Users can expand the group to see all the notifications it contains and dismiss the group as a whole.

应用还可以按线程对通知进行分组,使用户能够更轻松地找到所需的特定信息并与其进行交互。Apps can also group notifications by thread, making it easier for users to find and interact with the specific information they're interested in.

示例应用: GroupedNotificationsSample app: GroupedNotifications

若要了解如何对 Xamarin 使用分组通知,请查看GroupedNotifications示例应用。To learn how to use grouped notifications with Xamarin.iOS, take a look at the GroupedNotifications sample app.

此示例应用模拟与各个朋友的对话,发送每条消息的通知并按线程对消息进行分组。This sample app simulates conversations with various friends, sending a notification for each message and grouping them by thread. 它还演示了如何在应用程序级别的组中 unthreaded 通知。It also demonstrates how unthreaded notifications land in an application-level group.

本指南中的代码片段来自此示例应用。Code snippets in this guide come from this sample app.

请求授权并允许前台通知Request authorization and allow foreground notifications

在应用可以发送本地通知之前,它必须请求权限才能执行此操作。Before an app can send local notifications, it must request permission to do so. 在示例应用的AppDelegate中, FinishedLaunching方法请求此权限:In the sample app's AppDelegate, the FinishedLaunching method requests this permission:

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;
}

UNUserNotificationCenterDelegate (设置上述)决定了前台应用是否应通过调用传递到WillPresentNotification的完成处理程序来显示传入通知:The Delegate (set above) for a UNUserNotificationCenter decides whether or not a foreground app should display an incoming notification by calling the completion handler passed to WillPresentNotification:

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

UNNotificationPresentationOptions.Alert参数指示应用应显示警报,但不播放声音或更新徽章。The UNNotificationPresentationOptions.Alert parameter indicates that the app should show the alert but not play a sound or update a badge.

线程通知Threaded notifications

重复使用 Alice按钮点击示例应用的消息,让其使用名为 Alice 的朋友发送会话通知。Tap the sample app's Message with Alice button repeatedly to have it send notifications for a conversation with a friend named Alice. 由于此对话的通知是同一线程的一部分,因此锁屏界面和通知中心将它们组合在一起。Since this conversation's notifications are part of the same thread, the lock screen and Notification Center group them together.

若要开始与其他朋友的对话,请点击 "选择新朋友" 按钮。To start a conversation with a different friend, tap the Choose a new friend button. 此对话的通知显示在单独的组中。Notifications for this conversation appear in a separate group.

ThreadIdentifierThreadIdentifier

每当示例应用启动新线程时,它都会创建一个唯一的线程标识符:Any time the sample app starts a new thread, it creates a unique thread identifier:

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

若要发送线程通知,示例应用:To send a threaded notification, the sample app:

  • 检查应用是否有权发送通知。Checks whether the app has authorization to send a notification.
  • 创建UNMutableNotificationContentCreates a UNMutableNotificationContent 通知内容的对象并设置其ThreadIdentifierobject for the notification's content and sets its ThreadIdentifier 到上面创建的线程标识符。to the thread identifier created above.
  • 创建请求并计划通知:Creates a request and schedules the notification:
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);

    // ...
}

同一应用中具有相同线程标识符的所有通知都将出现在同一通知组中。All notifications from the same app with the same thread identifier will appear in the same notification group.

备注

若要在远程通知上设置线程标识符,请将 thread-id 项添加到通知的 JSON 有效负载中。To set a thread identifier on a remote notification, add the thread-id key to the notification's JSON payload. 有关更多详细信息,请参阅 Apple生成远程通知文档。See Apple's Generating a Remote Notification document for more details.

SummaryArgumentSummaryArgument

SummaryArgument 指定通知将如何影响通知所属的通知组左下角显示的摘要文本。SummaryArgument specifies how a notification will impact the summary text that appears on the lower-left corner of a notification group to which the notification belongs. iOS 将汇总文本从同一组中的通知聚合起来,以创建整体摘要说明。iOS aggregates summary text from notifications in the same group to create an overall summary description.

示例应用使用消息的作者作为 summary 参数。The sample app uses the message's author as the summary argument. 使用此方法时,使用 Alice 的六个通知组的摘要文本可能会有5 个来自 Alice 和我的通知Using this approach, the summary text for a group of six notifications with Alice might be 5 more notifications from Alice and Me.

Unthreaded 通知Unthreaded notifications

每点击一次示例应用的约会提醒按钮,都将发送各种约会提醒通知。Each tap of the sample app's Appointment reminder button sends one of various appointment reminder notifications. 由于这些提醒不是串接的,它们显示在锁屏界面和通知中心的应用程序级通知组中。Since these reminders are not threaded, they appear in the application-level notification group on the lock screen and in Notification Center.

若要发送 unthreaded 通知,示例应用的 ScheduleUnthreadedNotification 方法使用类似于上面的代码。To send an unthreaded notification, the sample app's ScheduleUnthreadedNotification method uses similar code as above. 但是,它不会对 UNMutableNotificationContent 对象设置 ThreadIdentifierHowever, it does not set the ThreadIdentifier on the UNMutableNotificationContent object.