Auto dismiss replaceable notifications (#711)

This commit is contained in:
Ross Savage
2025-02-04 16:53:40 +01:00
committed by GitHub
parent bf4a364c4b
commit d25598e6a4
19 changed files with 495 additions and 348 deletions

View File

@@ -10,6 +10,28 @@ public protocol TaskProtocol : EventListener {
}
extension TaskProtocol {
func removePushNotifications(threadIdentifier: String, logger: ServiceLogger) {
let semaphore = DispatchSemaphore(value: 0)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.getDeliveredNotifications(completionHandler: { notifications in
defer {
semaphore.signal()
}
let removableNotifications = notifications.filter({ $0.request.content.threadIdentifier == threadIdentifier })
guard !removableNotifications.isEmpty else {
return
}
// The call to removeDeliveredNotifications() is async in a background thread and
// needs to be complete before calling contentHandler()
notificationCenter.removeDeliveredNotifications(withIdentifiers: removableNotifications.map({ $0.request.identifier }))
logger.log(tag: "TaskProtocol", line:"removePushNotifications: \(removableNotifications.count)", level: "INFO")
})
semaphore.wait()
}
func displayPushNotification(title: String, body: String? = nil, logger: ServiceLogger, threadIdentifier: String? = nil) {
logger.log(tag: "TaskProtocol", line:"displayPushNotification \(title)", level: "INFO")
guard
@@ -18,6 +40,8 @@ extension TaskProtocol {
else {
return
}
removePushNotifications(threadIdentifier: Constants.NOTIFICATION_THREAD_REPLACEABLE, logger: logger)
if let body = body {
bestAttemptContent.body = body
@@ -28,6 +52,10 @@ extension TaskProtocol {
}
bestAttemptContent.title = title
contentHandler(bestAttemptContent)
// The call to contentHandler() needs to be done with a slight delay otherwise
// it will be killed before its finished removing the notifications
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
contentHandler(bestAttemptContent)
}
}
}