如何从IOS通知中心一一读取通知后清除通知?

问题描述 投票:1回答:3

在IOS应用中,是否有任何选项可以清除单个通知或在点击后将其标记为已读?我认为Apple不提供此功能。它们仅提供一次清除所有通知的功能。我搜索了很多,但没有找到任何解决方案。尽管我发现某些应用程序(例如Gmail)一次清除了一条通知。

提前感谢!

iphone ios notifications push clear
3个回答
1
投票

您可以在此属性中设置号码

 [UIApplication sharedApplication].applicationIconBadgeNumber

例如,将其减少一

[UIApplication sharedApplication].applicationIconBadgeNumber -= 1;

将其设置为特定值

[UIApplication sharedApplication].applicationIconBadgeNumber = 5;

1
投票

我不知道如何处理推送通知,但是您可以像这样取消单个本地通知:

[[UIApplication sharedApplication] cancelLocalNotification:notification];

您可以获取对由App Delegate application:DidReceiveLocalNotification方法窃听的通知的引用。


0
投票

请注意,此答案使用的是Swift 5

要在点击时清除单个通知,您可以按照两个步骤进行操作:然后,清除匹配的通知。

我在其他地方回答了如何extend UNUserNotificationCenter to remove notifications和徽章。看起来像这样:

UNUserNotificationCenter

有了此扩展名,我们想响应extension UNUserNotificationCenter { func decreaseBadgeCount(by notificationsRemoved: Int) { DispatchQueue.main.async { UIApplication.shared.applicationIconBadgeNumber -= notificationsRemoved } } func removeNotifications(_ notifications: [UNNotification], decreaseBadgeCount: Bool = true) { let identifiers = notifications.map { $0.request.identifier } UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: identifiers) if decreaseBadgeCount { self.decreaseBadgeCount(by: notifications.count) } } func removeNotifications<T: Comparable>(whereKey key: AnyHashable, hasValue value: T, decreaseBadgeCount: Bool = true) { UNUserNotificationCenter.current().getDeliveredNotifications { notifications in let notificationsToRemove = notifications.filter { guard let userInfoValue = $0.request.content.userInfo[key] as? T else { return false } return userInfoValue == value } self.removeNotifications(notificationsToRemove, decreaseBadgeCount: decreaseBadgeCount) } } func removeNotifications(withThreadIdentifier threadIdentifier: String, decreaseBadgeCount: Bool = true) { UNUserNotificationCenter.current().getDeliveredNotifications { notifications in let notificationsToRemove = notifications.filter { $0.request.content.threadIdentifier == threadIdentifier } self.removeNotifications(notificationsToRemove, decreaseBadgeCount: decreaseBadgeCount) } } func removeNotification(_ notification: UNNotification, decreaseBadgeCount: Bool = true) { removeNotifications([notification], decreaseBadgeCount: decreaseBadgeCount) } } 中的敲击,特别是AppDelegate方法:

userNotificationCenter(_:didReceive:withCompletionHandler:)

请注意,这仅适用于iOS 10及更高版本,并且不为@available(iOS 10, *) extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { UNUserNotificationCenter.current().removeNotification(response.notification) completionHandler() } } 参数提供false值,会将应用程序图标上的标志减少一。

编辑:不要忘记也将decreaseBadgeCount设置为AppDelegate委托:

UNUserNotificationCenter
© www.soinside.com 2019 - 2024. All rights reserved.