ios通知的创建与移除_在iOS 10中使用UNUserNotificationCenterDelegate收到新通知时,如何删除以前发送的通知?...
时间: 2024-01-21 19:16:25 浏览: 24
在iOS 10及以后的版本中,可以使用UNUserNotificationCenterDelegate协议的userNotificationCenter(_:didReceive:withCompletionHandler:)方法来处理新通知的接收,并在需要的情况下删除以前发送的通知。
具体步骤如下:
1. 在AppDelegate中设置UNUserNotificationCenter的delegate:
```
UNUserNotificationCenter.current().delegate = self
```
2. 实现UNUserNotificationCenterDelegate协议的userNotificationCenter(_:didReceive:withCompletionHandler:)方法:
```
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// 处理新通知的接收
// ...
// 删除以前发送的通知
let notificationId = "previous_notification_id"
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [notificationId])
// 调用completionHandler,告诉系统已经处理完通知
completionHandler()
}
```
在上面的代码中,我们首先处理新通知的接收,然后调用UNUserNotificationCenter的removeDeliveredNotifications(withIdentifiers:)方法来删除以前发送的通知。这个方法接受一个通知ID的数组作为参数,表示要删除哪些通知。
最后,我们需要在方法的最后调用completionHandler(),告诉系统已经处理完通知。这个方法是一个闭包,需要在方法结束时调用,否则系统会认为通知没有被处理,导致通知栏上的通知一直存在。
需要注意的是,removeDeliveredNotifications(withIdentifiers:)方法只能删除已经发送并且已经显示在通知栏上的通知,不能删除尚未发送或者已经被用户手动删除的通知。如果需要删除尚未发送的通知,可以使用UNUserNotificationCenter的removePendingNotificationRequests(withIdentifiers:)方法。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)