如何获取本地通知点击操作按钮对应的UNNotificationRequest标识符
问题解答
完全可以实现该需求,通过 UNUserNotificationCenter 的代理方法就能直接获取到点击操作按钮对应通知的所有关联信息。
实现逻辑说明
1. 基础配置
- 首先让需要处理通知回调的类遵守
UNUserNotificationCenterDelegate协议,通常可以在AppDelegate或者专门负责通知管理的工具类中实现。 - 应用启动时提前注册代理,建议放在
didFinishLaunchingWithOptions方法中执行,避免代理未注册导致回调丢失:
UNUserNotificationCenter.current().delegate = self
2. 核心回调方法
当用户点击通知的任意操作按钮(包括点击通知本身、关闭按钮)时,都会触发下方代理方法,你可以直接在方法内拿到需要的所有信息:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 获取对应通知的UNNotificationRequest实例 let targetRequest = response.notification.request // 拿到通知的唯一标识符 let notificationIdentifier = targetRequest.identifier // 拿到通知的全部内容:标题、副标题、自定义附加信息等 let notificationContent = targetRequest.content let customInfo = notificationContent.userInfo // 拿到用户点击的操作按钮的唯一标识符 let clickedActionId = response.actionIdentifier // 在这里处理你的业务逻辑 completionHandler() }
- 系统默认操作的标识符说明:点击通知本身的ID为
UNNotificationDefaultActionIdentifier,点击关闭按钮的ID为UNNotificationDismissActionIdentifier,你自定义的操作按钮ID就是注册时设置的对应字符串。
注意事项
如果需要支持应用在前台运行时也能正常接收通知、触发回调,需要同时实现另一个代理方法:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // 可自定义前台展示的通知样式 completionHandler([.banner, .sound]) }
所有带操作按钮的通知类别,需要提前通过 UNUserNotificationCenter.current().setNotificationCategories(_:) 方法注册,否则操作按钮不会展示,对应的点击回调也不会触发。
内容的提问来源于stack exchange,提问作者jat
相关产品推荐
相关产品推荐

