ios通知的创建与移除_在iOS 10中使用UNUserNotificationCenterDelegate收到新通知时,如何删除以前发送的通知?...
时间: 2024-02-01 21:13:16 浏览: 16
在iOS 10及以上版本中,可以使用`UNUserNotificationCenterDelegate`协议的`userNotificationCenter(_:didReceive:withCompletionHandler:)`方法来接收到新通知。如果您想要在接收到新通知时删除以前发送的通知,可以使用`UNUserNotificationCenter`类提供的`removeDeliveredNotifications(withIdentifiers:)`方法。
具体实现如下:
1. 在您的`AppDelegate`类中,将`UNUserNotificationCenterDelegate`设置为应用的通知中心的代理:
```
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.delegate = self
// ...
return true
}
}
```
2. 实现`UNUserNotificationCenterDelegate`协议的`userNotificationCenter(_:didReceive:withCompletionHandler:)`方法:
```
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let notificationIdentifier = response.notification.request.identifier
let center = UNUserNotificationCenter.current()
center.removeDeliveredNotifications(withIdentifiers: [notificationIdentifier])
completionHandler()
}
```
在这个方法中,获取到`response`参数中通知的唯一标识符,并使用`UNUserNotificationCenter`类的`removeDeliveredNotifications(withIdentifiers:)`方法来删除以前发送的通知。最后,一定要调用`completionHandler()`方法来告诉系统已经处理完通知了。
注意:这个方法只会在用户点击通知时被调用,如果用户直接在通知中心中清除了通知,这个方法并不会被调用。