Xamarin.iOS 中的互動式通知用戶介面
iOS 10 中引進的通知內容延伸模組可讓您建立通知的自定義使用者介面。 從 iOS 12 開始,通知使用者介面可以包含互動式元素,例如按鈕和滑桿。
通知內容延伸模組 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中定義的處理程式產生關聯:
啟動應用程式按鈕處理程式會在 上
ExtensionContext
呼叫PerformNotificationDefaultAction
動作方法,以啟動應用程式: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; }