Xamarin.iOS 中的交互式通知用户界面

iOS 10 中引入的通知内容扩展允许为通知创建自定义用户界面。 从 iOS 12 开始,通知用户界面可以包含按钮和滑块等交互式元素。

示例应用:RedGreenNotifications

RedGreenNotifications 示例应用包含具有交互式用户界面的通知内容扩展。

本指南中的代码片段来自此示例。

通知内容扩展 Info.plist 文件

在示例应用中,RedGreenNotificationsContentExtension 项目中的 Info.plist 文件包含以下配置:

<!-- ... -->
<key>NSExtension</key>
<dict>
    <key>NSExtensionAttributes</key>
    <dict>
        <key>UNNotificationExtensionCategory</key>
        <array>
            <string>red-category</string>
            <string>green-category</string>
        </array>
        <key>UNNotificationExtensionUserInteractionEnabled</key>
        <true/>
        <key>UNNotificationExtensionDefaultContentHidden</key>
        <true/>
        <key>UNNotificationExtensionInitialContentSizeRatio</key>
        <real>0.6</real>
    </dict>
    <key>NSExtensionMainStoryboard</key>
    <string>MainInterface</string>
    <key>NSExtensionPointIdentifier</key>
    <string>com.apple.usernotifications.content-extension</string>
    <key></key>
    <true/>
</dict>
<!-- ... -->

请注意以下功能:

  • 数组 UNNotificationExtensionCategory 指定内容扩展处理的通知类别的类型。
  • 为了支持交互式内容,通知内容扩展将 UNNotificationExtensionUserInteractionEnabled 键设置为 true
  • UNNotificationExtensionInitialContentSizeRatio 指定内容扩展接口的初始高度/宽度比率。

交互式接口

MainInterface.storyboard(定义通知内容扩展的接口)是包含单个视图控制器的标准情节提要。 在示例应用中,视图控制器的类型 NotificationViewController为 ,它包含一个图像视图、三个按钮和一个滑块。 情节提要将这些控件与 NotificationViewController.cs 中定义的处理程序相关联:

  • “启动应用”按钮处理程序调用 PerformNotificationDefaultAction 上的 ExtensionContext操作方法,这将启动应用:

    partial void HandleLaunchAppButtonTap(UIButton sender)
    {
        ExtensionContext.PerformNotificationDefaultAction();
    }
    

    在应用中,用户通知中心 Delegate (示例应用中, AppDelegate) 可以响应 方法中的 DidReceiveNotificationResponse 交互:

    [Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
    public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, System.Action completionHandler)
    {
        if (response.IsDefaultAction)
        {
            Console.WriteLine("ACTION: Default");
            // ...
    
  • 关闭通知按钮处理程序在 上ExtensionContext调用 DismissNotificationContentExtension ,这会关闭通知:

    partial void HandleDismissNotificationButtonTap(UIButton sender)
    {
        ExtensionContext.DismissNotificationContentExtension();
    }
    
  • “删除通知”按钮处理程序会消除通知,并将其从通知中心中删除:

    partial void HandleRemoveNotificationButtonTap(UIButton sender)
    {
        ExtensionContext.DismissNotificationContentExtension();
        UNUserNotificationCenter.Current.RemoveDeliveredNotifications(new string[] { notification.Request.Identifier });
    }
    
  • 处理滑块上的值更改的方法更新通知界面中显示的图像的 alpha:

    partial void HandleSliderValueChanged(UISlider sender)
    {
        Xamagon.Alpha = sender.Value;
    }