在iOS上禁用默认通知警报视图,可以通过以下步骤实现:
didFinishLaunchingWithOptions
方法。UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// 禁用默认通知警报视图
completionHandler([])
}
UNUserNotificationCenterDelegate
协议,并在didFinishLaunchingWithOptions
方法中设置UNUserNotificationCenter.current().delegate = self
。完整的代码示例:
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
UNUserNotificationCenter.current().delegate = self
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// 禁用默认通知警报视图
completionHandler([])
}
}
这样,当应用程序在前台运行时,将不会显示默认的通知警报视图,而是可以自定义处理远程通知的展示方式。
领取专属 10元无门槛券
手把手带您无忧上云