在iOS中,本地通知按钮的点击事件是通过实现UNUserNotificationCenterDelegate
协议中的userNotificationCenter(_:didReceive:withCompletionHandler:)
方法来处理的。在这个方法中,您可以根据按钮的标识符执行相应的操作。
下面是一个示例代码,演示如何在用户点击本地通知按钮时执行相应的操作:
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 设置UNUserNotificationCenter的delegate
UNUserNotificationCenter.current().delegate = self
return true
}
// 在用户点击本地通知按钮时调用
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// 获取按钮的标识符
let actionIdentifier = response.actionIdentifier
// 判断按钮的标识符,并执行相应的操作
switch actionIdentifier {
case "Action1":
// 执行操作1
print("执行操作1")
case "Action2":
// 执行操作2
print("执行操作2")
default:
break
}
// 完成处理
completionHandler()
}
}
在上面的代码中,我们首先将UNUserNotificationCenter
的delegate设置为AppDelegate
,然后在userNotificationCenter(_:didReceive:withCompletionHandler:)
方法中根据按钮的标识符执行相应的操作。
请注意,您需要在Info.plist
文件中添加UIBackgroundModes
键并将其值设置为remote-notification
,以便应用可以在后台接收本地通知并执行相应的操作。
希望这个示例可以帮助您解决问题!