使用者通知架構允許傳遞和處理本機和遠端通知。 使用此架構,應用程式或應用程式延伸模組可以藉由指定一組條件,例如位置或一天中的時間,來排程本機通知的傳遞。
此外,當應用程式或擴充功能傳遞至使用者的裝置時,應用程式或擴充功能可以接收本機和遠端通知(並可能修改)。
使用者通知 UI 架構可讓應用程式或應用程式延伸模組在向用戶呈現時自定義本機和遠端通知的外觀。
此架構提供下列方式,讓應用程式可以將通知傳遞給使用者:
- 視覺警示:通知會從畫面頂端向下滾下來作為橫幅。
- 音效和震動:可以與通知產生關聯。
- 應用程式圖示徽章顯示:應用程式的圖示會顯示一個徽章,提示有可用的新內容,例如未讀的電子郵件訊息數目。
此外,視使用者目前的內容而定,將會以不同的方式呈現通知:
- 如果裝置解除鎖定,通知會從畫面頂端向下滾下來作為橫幅。
- 如果裝置已鎖定,通知將會顯示在用戶的鎖定畫面上。
- 如果使用者錯過通知,他們可以開啟通知中心並檢視任何可用的等候通知。
應用程式可以傳送兩種類型的使用者通知:
- 本機通知:這些是由在用戶裝置本機安裝的應用程式所傳送。
- 遠端通知:會從遠端伺服器傳送,並呈現給使用者,或觸發應用程式內容的背景更新。
關於本地通知
應用程式可傳送的本機通知具有下列功能和屬性:
- 這些應用程式是由用戶裝置上的本機應用程式傳送。
- 它們可以設定為使用時間或位置型觸發機制。
- 應用程式會在使用者的裝置上排程通知,並在觸發條件滿足時顯示。
- 當使用者與通知互動時,應用程式會收到回呼。
本機通知的一些範例包括:
- 行事曆警示。
- 提醒通知。
- 位置感知觸發器。
如需詳細資訊,請參閱Apple 的使用者通知 檔。
關於遠端通知
應用程式可傳送的遠端通知具有下列功能和屬性:
- 應用程式具有與其通訊的伺服器端元件。
- Apple 推播通知服務 (APNs) 可用來從開發人員的雲端式伺服器將遠端通知傳遞至使用者的裝置。
- 當應用程式收到遠端通知時,它會顯示給使用者。
- 當使用者與通知互動時,應用程式會收到回呼。
遠端通知的一些範例包括:
- 新聞警示。
- 體育更新。
- 即時通訊訊息。
應用程式可以使用兩種類型的遠端通知:
- 使用者面向:這些會顯示給裝置上的使用者。
- 無訊息更新:這些會提供一種機制來更新背景中應用程式的內容。 收到無訊息更新時,應用程式可以連絡遠端伺服器,以提取最新的內容。
如需詳細資訊,請參閱Apple 的使用者通知 檔。
UIApplication API
您可以使用 UIApplication 向系統註冊通知,並排程該通知的觸發方式-時間或位置(這是 Apple 提供給使用者通知的原始 API)。
不過,使用 UIApplication 所提供的現有通知時,開發人員可能會遇到數個問題:
- 本機或遠端通知需要不同的回呼,可能會導致程式代碼重複。
- 應用程式在系統排程通知之後,對通知的控制有限。
- 所有 Apple 現有平臺都有不同的支援層級。
關於使用者通知架構
為了改善通知的體驗,Apple 引進了使用者通知架構,以取代上述現有的 UIApplication 方法。
使用者通知架構提供以下功能:
- 熟悉的 API,其中包含與先前方法的功能同位,可讓您輕鬆地從現有的架構移植程式碼。
- 包含擴充的內容選項集,可讓更豐富的通知傳送給使用者。
- 本機和遠端通知都可以由相同的程式碼和回呼處理。
- 簡化處理使用者與通知互動時傳送至應用程式的回呼過程。
- 增強對擱置和已傳遞通知的管理,包括移除或更新通知的能力。
- 新增進行應用程式內通知呈現的功能。
- 增強應用程式延伸模組中排程和處理通知的能力。
- 新增通知功能的新擴充點。
使用者通知架構會跨 Apple 支援的多個平臺提供統一的通知 API,包括:
- iOS:管理及排程通知的完整支援。
- tvOS:新增為本機和遠端通知的應用程式圖示添加徽章的功能。
- Mac Catalyst:完整支援通知的管理和排程。
- macOS:管理及排程通知的完整支援。
如需詳細資訊,請參閱Apple的使用者 通知 和 使用者通知UI 檔。
準備通知傳遞
應用程式必須先向系統註冊應用程式,應用程式才能將通知傳送給使用者,而且因為通知對使用者造成中斷,應用程式必須先明確要求許可權,才能傳送。
使用者可核准應用程式的通知要求有三個不同層級:
- 橫幅展示。
- 音效警示。
- 為應用程式圖示添加標記。
此外,必須針對本機和遠端通知要求和設定這些核准層級。
只要應用程式啟動時,應要求通知許可權,方法是將下列程式代碼新增至 FinishedLaunching 的方法 AppDelegate ,並設定所需的通知類型 (UNAuthorizationOptions):
using UserNotifications;
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
// Request notification permissions from the user
UNUserNotificationCenter.Current.RequestAuthorization (UNAuthorizationOptions.Alert, (approved, error) => {
// Handle approval (or disapproval)
});
return true;
}
在macOS上,在DidFinishLaunching實作中完成此操作:
using UserNotifications;
public override void DidFinishLaunching (NSNotification notification)
{
// Request notification permissions from the user
UNUserNotificationCenter.Current.RequestAuthorization (UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (approved, error) => {
// Handle approval (or disapproval)
});
}
備註
macOS 和 Mac Catalyst 應用程式必須簽署,才能顯示許可權對話方塊,即使以偵錯模式在本機建置也一樣。
將項目檔中的 EnableCodeSigning 屬性設定為 true ,以強制簽署應用程式。
此外,用戶隨時都可以使用裝置上的 [設定 ] 應用程式來 變更應用程式的通知許可權。 應用程式應該先檢查使用者所要求的通知許可權,再使用下列程式代碼來呈現通知:
// Get current notification settings
UNUserNotificationCenter.Current.GetNotificationSettings ((settings) => {
var alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);
});
啟用背景通知
為了讓應用程式接收背景通知,它必須啟用遠端通知背景模式給應用程式。
這可藉由將專案新增 remote-notifications 至 UIBackgroundModes 專案 Info.plist 檔案中的陣列來完成,如下所示:
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
設定遠端通知環境
開發人員必須通知 OS 在 中執行的環境推播通知為 development 或 production。 若未提供這項資訊,可能會導致應用程式在提交至 App Store 時遭到拒絕,通知類似如下:
缺少推播通知權限 - 您的應用程式包含 Apple 推播通知服務的 API,但應用程式簽章中缺少
aps-environment權限。
若要提供必要的權利,請執行下列動作:
在您選擇的文字編輯器中開啟項目檔。
輸入兩個
CustomEntitlements項目,如下所示:<ItemGroup> <CustomEntitlements Include="aps-environment" Type="String" Value="development" Condition="'$(Configuration)' != 'Release'" /> <CustomEntitlements Include="aps-environment" Type="String" Value="production" Condition="'$(Configuration)' == 'Release'" /> </ItemGroup>注意:如果您使用與
Release發佈至 App Store 不同的設定,請據以更新條件。
備註
aps-environment也可以在 Entitlements.plist 檔案中設定,這在過去是通常的做法。 使用專案檔的優點是可以更輕鬆地根據組建配置,自動使用權利的正確值,development 或 production。
資源配置
上一節的 aps-environment 權限需要使用具有 Push Notifications 功能的配置檔:
移至 Apple Developer 網站的 [標識符] 區段:
新增識別碼(註冊新標識碼):
選取[應用程式] 類型:
輸入新應用程式識別碼的套件組合識別碼和描述:
啟用
Push Notifications功能:按一下
Register以儲存新的應用程式識別碼。
下一個步驟是建立新應用程式識別碼的佈建設定檔:
移至 Apple Developer 網站的 [設定檔] 區段:
新增 iOS 應用程式開發的描述檔。
選取我們剛才建立的應用程式識別碼:
選取此佈建配置檔中包含的所有憑證(如果尚未建立任何憑證,就必須建立新的憑證):
選取此佈建配置檔中包含的所有裝置(應用程式只能安裝在這些裝置上)。
選擇佈建描述檔的名稱並檢閱。
產生並下載新的設定檔。
在 Xcode 中開啟下載的布建配置檔檔案(在 Finder 中按兩下它),將它安裝到系統中。
將專案設定為使用新建立的佈建設定檔,具體方法是將
CodesignProvision屬性設為步驟 6 中的佈建設定檔名稱:<PropertyGroup> <CodesignProvision>User Notifications Profile</CodesignProvision> </PropertyGroup>
備註
如果應用程式有任何處理通知的應用程式延伸模組,則每個對應的應用程式延伸模組專案都必須重複此程式 -- 它們必須各自有自己的應用程式識別碼和布建配置檔。
註冊遠端通知
如果應用程式將傳送和接收遠端通知,它仍然需要使用現有的 UIApplication API 進行令牌註冊。 此註冊需要裝置具有即時網路連線才能存取APN,這會產生將傳送至應用程式的必要令牌。 然後,應用程式必須將此令牌轉送給開發人員的伺服器端應用程式,以註冊遠端通知:
使用下列程式代碼來初始化必要的註冊:
UIApplication.SharedApplication.RegisterForRemoteNotifications ();
向開發人員伺服器端應用程式發送的令牌需要作為通知負載的一部分,當從伺服器發送遠端通知到 APNs 時需要包含該令牌。
令牌可作為將通知與用來開啟或回應通知的應用程式系結在一起的密鑰。
如需詳細資訊,請參閱Apple 的使用者通知 檔。
通知傳遞
應用程式已完整註冊,以及使用者要求和授與的必要許可權,應用程式現在已準備好傳送和接收通知。
提供通知內容
所有通知均包含標題和子標題,並會與通知內容的本文一同顯示。 您也可以將 媒體附件 新增至通知內容。
若要建立本機通知的內容,請使用下列程序代碼:
var content = new UNMutableNotificationContent();
content.Title = "Notification Title";
content.Subtitle = "Notification Subtitle";
content.Body = "This is the message body of the notification.";
content.Badge = 1;
針對遠端通知,其過程是類似的:
{
"aps":{
"alert":{
"title":"Notification Title",
"subtitle":"Notification Subtitle",
"body":"This is the message body of the notification."
},
"badge":1
}
}
傳送通知時的排程
建立通知的內容后,應用程式必須藉由設定 觸發程式來排程通知何時向用戶顯示。 有四種不同的觸發類型:
- 推播通知 - 與遠端通知獨佔搭配使用,並在 APN 將通知套件傳送至裝置上執行的應用程式時觸發。
- 時間間隔 - 允許從時間間隔開始排程本機通知,並結束一些未來點。 例如:
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger (5, false); - 行事曆日期 - 允許在特定的日期和時間排程本機通知。
- 位置為基礎 - 允許排程本機通知,當進入或離開特定地理位置或在任何藍牙信標的鄰近位置時。
當本機通知就緒時,應用程式必須呼叫 UNUserNotificationCenter.AddNotificationRequest 排程其向用戶顯示。 針對遠端通知,伺服器端應用程式會將通知承載傳送至 APN,然後將封包傳送至使用者的裝置。
將所有部分整合在一起,範例本機通知可能如下所示:
using UserNotifications;
public void SendLocalNotification ()
{
var content = new UNMutableNotificationContent ();
content.Title = "Notification Title";
content.Subtitle = "Notification Subtitle";
content.Body = "This is the message body of the notification.";
content.Badge = 1;
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger (5, false);
var requestId = "sampleRequest";
var request = UNNotificationRequest.FromIdentifier (requestId, content, trigger);
UNUserNotificationCenter.Current.AddNotificationRequest (request, (err) => {
if (err is not null) {
// Do something with error
}
});
}
觸發遠端通知
有多種方式可在開發期間觸發遠端通知以進行測試:
- Apple 的推播通知主控台
- 命令行工具
- 其他第三方解決方案。
應用程式發行后,通常會從伺服器端應用程式觸發遠端通知。
處理前景應用程式通知
當應用程式位於前景且觸發通知時,應用程式可以以不同的方式處理通知。 藉由提供 UNUserNotificationCenterDelegate 並實作 WillPresentNotification 方法,應用程式可以接管顯示通知的責任。 例如:
using System;
using UserNotifications;
public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
{
#region Constructors
public UserNotificationCenterDelegate ()
{
}
#endregion
#region Override Methods
public override void WillPresentNotification (UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
// Do something with the notification
Console.WriteLine ("Active notification: {0}", notification);
// Tell system to display the notification anyway or use
// `None` to say we have handled the display locally.
completionHandler (UNNotificationPresentationOptions.Alert);
}
#endregion
}
此程式代碼只會將 UNNotification 的內容寫到應用程式輸出,並要求系統顯示通知的標準警示。
如果應用程式想要在前景顯示通知本身,而不要使用系統預設值,請將 None 傳遞至完成處理程式。 範例:
completionHandler (UNNotificationPresentationOptions.None);
在此程式代碼就緒后,請開啟 AppDelegate.cs 檔案進行編輯,並變更 FinishedLaunching 方法,如下所示:
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
// Request notification permissions from the user
UNUserNotificationCenter.Current.RequestAuthorization (UNAuthorizationOptions.Alert, (approved, err) => {
// Handle approval
});
// Watch for notifications while the app is active
UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate ();
return true;
}
此程式代碼會將上述的自定義 UNUserNotificationCenterDelegate 附加至目前的 UNUserNotificationCenter ,讓應用程式可以在作用中且處於前景時處理通知。
通知管理
通知管理可讓您存取擱置和傳遞的通知,並新增移除、更新或升級這些通知的能力。
通知管理的一個重要部分是使用系統建立和排程通知時指派給通知 的要求標識符 。 針對遠端通知,這會透過 apps-collapse-id HTTP 要求標頭中的欄位指派。
要求標識碼是用來選取應用程式想要執行通知管理的通知。
拿掉通知
若要從系統移除擱置的通知,請使用下列程序代碼:
var requests = new string [] { "sampleRequest" };
UNUserNotificationCenter.Current.RemovePendingNotificationRequests (requests);
若要移除已傳遞的通知,請使用下列程序代碼:
var requests = new string [] { "sampleRequest" };
UNUserNotificationCenter.Current.RemoveDeliveredNotifications (requests);
更新現有的通知
若要更新現有的通知,只要使用修改所需的參數來建立新的通知(例如新的觸發時間),並將它新增至系統,其要求標識符與需要修改的通知相同。 範例:
using UserNotifications;
// Rebuild notification
var content = new UNMutableNotificationContent ();
content.Title = "Notification Title";
content.Subtitle = "Notification Subtitle";
content.Body = "This is the message body of the notification.";
content.Badge = 1;
// New trigger time
var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger (10, false);
// Id of notification to be updated
var requestId = "sampleRequest";
var request = UNNotificationRequest.FromIdentifier (requestId, content, trigger);
// Add to system to modify existing Notification
UNUserNotificationCenter.Current.AddNotificationRequest (request, (err) => {
if (err != null) {
// Do something with error...
}
});
針對已傳遞的通知,如果使用者已經讀取通知,現有的通知將會更新並升階到 [首頁] 和 [鎖定] 畫面上列表頂端。
使用通知動作
傳遞給使用者的通知不是靜態的,並提供數種方式讓使用者可以與其互動(從內建到自定義動作)。
應用程式可以回應的動作有三種類型:
- 默認動作 - 這是當使用者點選通知以開啟應用程式並顯示指定通知的詳細數據時。
- 自定義動作 - 這些動作可讓使用者直接從通知執行自定義工作,而不需要啟動應用程式。 這些按鈕可以呈現為具有可自定義標題的按鈕清單,或可在背景中執行的文字輸入欄位(其中應用程式在滿足要求時提供少量時間)或前景(在前景啟動應用程式以完成要求)。
- 關閉動作 - 當使用者關閉指定的通知時,此動作會傳送至應用程式。
建立自訂動作
若要建立及註冊系統自定義動作,請使用下列程式代碼:
// Create action
var actionId = "reply";
var title = "Reply";
var action = UNNotificationAction.FromIdentifier (actionId, title, UNNotificationActionOptions.None);
// Create category
var categoryId = "message";
var actions = new UNNotificationAction [] { action };
var intentIds = new string [] { };
var categoryOptions = new UNNotificationCategoryOptions [] { };
var category = UNNotificationCategory.FromIdentifier (categoryId, actions, intentIds, UNNotificationCategoryOptions.None);
// Register category
var categories = new UNNotificationCategory [] { category };
UNUserNotificationCenter.Current.SetNotificationCategories (new NSSet<UNNotificationCategory>(categories));
建立新的 UNNotificationAction 時,會獲派唯一標識符和按鈕上出現的標題。 根據預設,動作會建立為背景動作,不過可以提供選項來調整動作的行為(例如將它設定為前景動作)。
建立的每個動作都必須與類別相關聯。 建立新的 UNNotificationCategory 時,會指派唯一標識碼、可執行的動作清單、意圖標識符清單,以提供類別中動作意圖的詳細資訊,以及控制類別行為的某些選項。
最後,所有類別都會使用 SetNotificationCategories 方法向系統註冊。
呈現自定義動作
建立並註冊系統一組自定義動作和類別之後,即可從本機或遠端通知呈現它們。
針對遠端通知,請在遠端通知承載中設定 category ,其符合上述其中一個類別。 例如:
{
aps: {
alert:"Hello world!",
category:"message"
}
}
針對本機通知,設定 CategoryIdentifier 對象的屬性 UNMutableNotificationContent 。 例如:
var content = new UNMutableNotificationContent ();
content.Title = "Notification Title";
content.Subtitle = "Notification Subtitle";
content.Body = "This is the message body of the notification.";
content.Badge = 1;
content.CategoryIdentifier = "message";
同樣地,此標識碼必須符合上面所建立的其中一個類別。
處理關閉動作
如上所述,當使用者關閉通知時,可以傳送關閉動作給應用程式。 由於這不是標準動作,因此必須在建立類別時設定選項。 例如:
var categoryId = "message";
var actions = new UNNotificationAction [] { action };
var intentIds = new string [] { };
var categoryOptions = new UNNotificationCategoryOptions [] { };
var category = UNNotificationCategory.FromIdentifier (categoryId, actions, intentIds, UNNotificationCategoryOptions.CustomDismissAction);
處理行動回應
當使用者與上面建立的自定義動作和類別互動時,應用程式必須滿足要求的工作。 做法是提供 [UNUserNotificationCenterDelegate][unnsernotificationcenterdelegate],並實作 DidReceiveNotificationResponse 方法。 例如:
using System;
using UserNotifications;
namespace MonkeyNotification
{
public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
{
...
#region Override methods
public override void DidReceiveNotificationResponse (UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
// Take action based on Action ID
switch (response.ActionIdentifier) {
case "reply":
// Do something
break;
default:
// Take action based on identifier
if (response.IsDefaultAction) {
// Handle default action...
} else if (response.IsDismissAction) {
// Handle dismiss action
}
break;
}
// Inform caller it has been handled
completionHandler();
}
#endregion
}
}
傳入的 UNNotificationResponse 類別具有一個ActionIdentifier 屬性,該屬性可以是預設動作或取消動作。 使用 response.Notification.Request.Identifier 來測試任何自定義動作。
屬性 UserText 會保留任何使用者文字輸入的值。 屬性 Notification 保存著原始通知,其中包含包含觸發條件和通知內容的要求。 應用程式可以根據觸發程式類型來決定它是否為本機或遠端通知。
使用通知服務延伸模組
使用遠端通知時, 通知服務延伸模組 會提供一種方式,在通知承載內啟用端對端加密。 通知服務延伸模組是在背景中執行的非使用者介面延伸模組,主要目的是在向使用者呈現通知之前,先增強或取代通知的可見內容。
通知服務延伸模組旨在快速運行,而且系統只會提供有限時間執行。 如果通知服務擴充功能在分配的時間量中無法完成其工作,將會呼叫後援方法。 如果後援失敗,則會向用戶顯示原始通知內容。
通知服務延伸模組的一些可能用途包括:
- 提供遠端通知內容的端對端加密。
- 將附件新增至遠端通知以擴充它們。
實作通知服務延伸模組
若要在應用程式中實作通知服務延伸模組,請執行下列動作:
在主項目的資料夾旁邊,建立延伸模組專案的新資料夾。 下列指示假定新的資料夾名稱為
MyNotificationServiceExtension。開啟終端機,然後執行:
dotnet new ios-notification-service-extension開啟主要項目的項目檔,然後新增:
<ItemGroup> <ProjectReference Include="..\MyNotificationServiceExtension\MyNotificationServiceExtension.csproj"> <IsAppExtension>true</IsAppExtension> </ProjectReference> </ItemGroup>現在建置主要專案,擴充專案也會建置並包含在最終應用程式套件組合中。
這很重要
由於 Mac 與任何連線裝置之間的互動方式變更,目前無法使用調試程式偵錯應用程式擴充功能。 如需 https://github.com/xamarin/xamarin-macios/issues/19484 詳細資訊,請參閱 up-to-date 資訊。
這表示偵錯應用程式延伸模組的最可靠方式是不幸地將 Console.WriteLine 語句新增至程式碼,然後在 裝置記錄檔中尋找這些語句。
這很重要
服務延伸模組的套件組合標識碼 (ApplicationId) 前面必須加上主要應用程式的套件組合識別碼。 例如,如果主要應用程式具有的套件組合標識符 com.xamarin.monkeynotify,服務延伸模組應該具有的套件組合標識符 com.xamarin.monkeynotify.monkeynotifyserviceextension。
通知服務延伸模組中有一個主要類別需要修改,以提供所需的功能。 例如:
using System;
using Foundation;
using UIKit;
using UserNotifications;
namespace MonkeyChatServiceExtension
{
[Register ("NotificationService")]
public class NotificationService : UNNotificationServiceExtension
{
protected NotificationServiceClass (NativeHandle handle) : base (handle)
{
// Note: this .ctor should not contain any initialization logic,
// it only exists so that the OS can instantiate an instance of this class.
}
public override void DidReceiveNotificationRequest (UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
{
// Called when the OS receives a notification that can be muteated
// Create a mutable copy of the notification
var mutableRequest = (UNMutableNotificationContent) request.Content.MutableCopy ();
// Modify the notification content here...
mutableRequest.Title = $"[modified] {mutableRequest.Title}";
// Call the contentHandler callback to let the OS know about the modified notification.
contentHandler (mutableRequest);
}
public override void TimeWillExpire ()
{
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
}
}
}
第一個方法 DidReceiveNotificationRequest 會透過 request 對象傳遞通知標識碼和通知內容。 必須呼叫傳入 contentHandler 的 ,才能向用戶顯示通知。
第二個方法 TimeWillExpire 會在通知服務擴充功能的時間即將用完之前被呼叫,以處理該要求。 如果通知服務擴充功能在分配的時間量中無法呼叫 contentHandler ,則會向用戶顯示原始內容。
觸發通知服務擴充功能
使用應用程式建立並傳遞通知服務延伸模組之後,即可修改傳送至裝置的遠端通知承載來觸發它。 例如:
{
aps : {
alert : "New Message Available",
mutable-content: 1
},
encrypted-content : "#theencryptedcontent"
}
新的 mutable-content 金鑰會指定必須啟動通知服務延伸模組,才能更新遠端通知內容。 金鑰 encrypted-content 會保存通知服務延伸模組可以在向用戶呈現之前解密的加密數據。
請檢視下列通知服務延伸模組範例:
using UserNotification;
namespace myApp {
public class NotificationService : UNNotificationServiceExtension {
public override void DidReceiveNotificationRequest(UNNotificationRequest request, contentHandler) {
// Decrypt payload
var decryptedBody = Decrypt(Request.Content.UserInfo["encrypted-content"]);
// Modify notification body
var newContent = new UNMutableNotificationContent();
newContent.Body = decryptedBody;
// Present to user
contentHandler(newContent);
}
public override void TimeWillExpire() {
// Handle out-of-time fallback event
}
}
}
此程式代碼會從 encrypted-content 金鑰解密加密的內容、建立新的 UNMutableNotificationContent、將 Body 屬性設定為解密的內容,並使用 contentHandler 將通知呈現給使用者。