使用 iOS 12,應用程式可以傳送重大警示。 不論是否啟用「不要打擾」或響鈴開關關閉,重大警示都會播放音效。 這些通知是干擾性的,只有在用戶必須立即採取行動時,才應該使用。
自定義重大警示權利
若要在應用程式中顯示重大警示,請先 向Apple要求自定義重大警示通知權利 。
從 Apple 收到此權利並遵循有關如何設定應用程式以使用它的任何相關指示之後,請將自定義 權利 新增至您應用程式的 Entitlements.plist 檔案(s)。 然後,設定 iOS 套件組合簽署 選項,以在模擬器和裝置上簽署應用程式時使用 Entitlements.plist 。
要求授權
應用程式的通知授權要求會提示用戶允許或不允許應用程式的通知。 如果通知授權要求要求傳送重大警示的許可權,應用程式也會讓用戶有機會加入宣告重大警示。
下列程式代碼會藉由傳遞適當的來要求傳送重大警示和標準通知和音效的許可權 UNAuthorizationOptions 值至 RequestAuthorization:
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
UNUserNotificationCenter center = UNUserNotificationCenter.Current;
var options = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.CriticalAlert;
center.RequestAuthorization(options, (bool success, NSError error) => {
// ...
);
return true;
}
本機重大警示
若要傳送本機重大警示,請建立 UNMutableNotificationContent 並將其 屬性設定 Sound 為下列其中一項:
UNNotificationSound.DefaultCriticalSound,它會使用預設的重要通知音效。UNNotificationSound.GetCriticalSound,可讓您指定與您的應用程式和磁碟區搭配的自定義音效。
然後,從通知內容建立 UNNotificationRequest ,並將它新增至通知中心:
var content = new UNMutableNotificationContent()
{
Title = "Critical alert title",
Body = "Text of the critical alert",
CategoryIdentifier = "my-critical-alert-category",
// Sound = UNNotificationSound.DefaultCriticalSound
Sound = UNNotificationSound.GetCriticalSound("my_critical_sound.m4a", 1.0f)
};
var request = UNNotificationRequest.FromIdentifier(
Guid.NewGuid().ToString(),
content,
UNTimeIntervalNotificationTrigger.CreateTrigger(3, false)
);
var center = UNUserNotificationCenter.Current;
center.AddNotificationRequest(request, null);
重要
如果未為您的應用程式啟用重大警示,則不會傳遞這些警示。 除了應用程式第一次要求傳送重大警示許可權的提示,使用者也可以在 iOS 設定 應用程式的 [通知] 區段中啟用或停用重大警示。
遠端重大警示
如需遠端重大警示的相關信息,請參閱 WWDC 2018 的新功能使用者通知 工作階段和 產生遠端通知 檔。