在iOS中,可以使用UNUserNotificationCenterDelegate来监听和处理本地通知。当本地通知触发时,可以通过实现相应的代理方法来执行相应的动作。
以下是一个示例代码,在该代码中,我们创建了一个类遵循UNUserNotificationCenterDelegate协议,并实现了notificationCenter(_:didReceive:withCompletionHandler:)方法,当本地通知触发时,会执行该方法中的动作。
import UIKit
import UserNotifications
class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
func notificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// 在这里执行你的动作
print("本地通知被触发")
// 完成处理
completionHandler()
}
}
// 在AppDelegate中设置通知代理
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 注册通知
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
// 处理授权结果
if granted {
print("通知授权成功")
} else {
print("通知授权失败")
}
}
// 设置通知代理
UNUserNotificationCenter.current().delegate = NotificationDelegate()
return true
}
在以上代码中,我们创建了一个名为NotificationDelegate的类,并实现了notificationCenter(_:didReceive:withCompletionHandler:)方法。在这个方法中,你可以执行你想要的动作,例如弹出一个提示窗口、播放声音等。完成处理后,记得调用completionHandler()来通知系统已经处理完毕。
然后,在AppDelegate的application(_:didFinishLaunchingWithOptions:)方法中,我们设置了UNUserNotificationCenter的代理为我们刚刚创建的NotificationDelegate实例。
这样,当本地通知触发时,就会执行NotificationDelegate中的动作了。
下一篇:本地通知没有被添加