Removing Delivered Notifications (#1305)

* completed

* changelog

* tests

* more tests

* better naming

* fix

* a bit more waiting time

* generated mocks

* xcodegen
This commit is contained in:
Mauro
2023-07-11 10:44:06 +02:00
committed by GitHub
parent 98dabe8500
commit 28fa1140b7
15 changed files with 245 additions and 8 deletions
@@ -19,7 +19,7 @@ import Foundation
import UIKit
import UserNotifications
class NotificationManager: NSObject, NotificationManagerProtocol {
final class NotificationManager: NSObject, NotificationManagerProtocol {
private let notificationCenter: UserNotificationCenterProtocol
private let appSettings: AppSettings
@@ -31,6 +31,8 @@ class NotificationManager: NSObject, NotificationManagerProtocol {
appSettings: AppSettings) {
self.notificationCenter = notificationCenter
self.appSettings = appSettings
super.init()
addObservers()
}
// MARK: NotificationManagerProtocol
@@ -169,6 +171,47 @@ class NotificationManager: NSObject, NotificationManagerProtocol {
delegate?.unregisterForRemoteNotifications()
}
}
private func addObservers() {
NotificationCenter
.default
.publisher(for: .roomMarkedAsRead)
.sink { [weak self] notification in
guard let roomID = notification.object as? String else {
return
}
self?.removeMessageNotifications(for: roomID)
}
.store(in: &cancellables)
NotificationCenter
.default
.publisher(for: .invitesScreenAppeared)
.sink { [weak self] _ in
self?.removeInviteNotifications()
}
.store(in: &cancellables)
}
private func removeMessageNotifications(for roomID: String) {
Task {
let notificationsIdentifiers = await notificationCenter
.deliveredNotifications()
.filter { $0.request.content.roomID == roomID }
.map(\.request.identifier)
notificationCenter.removeDeliveredNotifications(withIdentifiers: notificationsIdentifiers)
}
}
private func removeInviteNotifications() {
Task {
let notificationsIdentifiers = await notificationCenter
.deliveredNotifications()
.filter { $0.request.content.categoryIdentifier == NotificationConstants.Category.invite }
.map(\.request.identifier)
notificationCenter.removeDeliveredNotifications(withIdentifiers: notificationsIdentifiers)
}
}
}
// MARK: - UNUserNotificationCenterDelegate
@@ -17,10 +17,14 @@
import Foundation
import UserNotifications
// Sadly we can't mock this because the delegate needs to be weak
// Use UserNotificationCenterSpy
protocol UserNotificationCenterProtocol: AnyObject {
var delegate: UNUserNotificationCenterDelegate? { get set }
func add(_ request: UNNotificationRequest) async throws
func requestAuthorization(options: UNAuthorizationOptions) async throws -> Bool
func deliveredNotifications() async -> [UNNotification]
func removeDeliveredNotifications(withIdentifiers identifiers: [String])
func setNotificationCategories(_ categories: Set<UNNotificationCategory>)
func authorizationStatus() async -> UNAuthorizationStatus
}