iOS开发:点击UNNotification后如何移除屏幕上的通知?
解决UNNotifications点击后残留的问题
嘿,我之前做Swift本地通知开发时也碰到过一模一样的坑!给你几个亲测有效的解决办法:
1. 处理通知时手动移除对应通知
不管是点击通知本体,还是点击自定义操作按钮,都可以在UNUserNotificationCenterDelegate的回调里主动删掉这条通知。代码写起来很简单:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 拿到当前通知的唯一标识符 let notificationId = response.notification.request.identifier // 移除这条已显示的通知 UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [notificationId]) // 千万别忘了调用completionHandler!系统靠这个确认你处理完了通知 completionHandler() }
2. 别漏了调用completionHandler
很多时候通知清不掉,都是因为忘了在回调里调用completionHandler()。系统需要这个信号来完成后续的通知清理流程,哪怕你没别的逻辑要处理,也必须加上这一行。
3. 检查自定义按钮的配置(如果有的话)
如果你给通知加了自定义操作按钮(比如“确认”“查看”这类),虽然系统默认点击操作按钮后会自动清通知,但保险起见,还是像上面那样手动移除更靠谱,避免出现意外残留。
另外,如果你需要一次性清空所有已显示的通知(比如用户进入APP首页时),可以用这个方法:
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
最后再提个小坑:一定要在AppDelegate的didFinishLaunchingWithOptions里设置好通知中心的Delegate,不然上面的回调根本不会触发:
UNUserNotificationCenter.current().delegate = self
内容的提问来源于stack exchange,提问作者karjeezy
相关产品推荐
相关产品推荐

