Reputation: 41
I have a SwiftUI app. I created a NotificationCenter
class to deliver local notifications, which includes the following function.
@MainActor
struct NotificationCenter {
// Remove deleted items from notification center
// Push all new and changed items to notification center
// Let notification center update changed items
static func pushNotifications(_ items: [Item]) async throws {
let center = UNUserNotificationCenter.current()
let items = Set(items)
let pending: Set<Item> = Set((await center.pendingNotificationRequests()).map{
Item(identifier: $0.identifier, notificationContent: $0.content)
})
let toBeRemovedPendingItems = pending.filter{ !items.map{ $0.id }.contains($0.id) }
let pushed: Set<Item> = Set((await center.deliveredNotifications()).map{
Item(identifier: $0.request.identifier, notificationContent: $0.request.content)
})
let toBeRemovedPushedItems = pushed.filter{ !items.map{ $0.id }.contains($0.id) }
let toBePushedItems = items
.subtracting(toBeRemovedPendingItems)
.subtracting((pushed.subtracting(toBeRemovedPushedItems)))
print(pushed)
print(toBePushedItems)
center.removePendingNotificationRequests(withIdentifiers: toBeRemovedPendingItems.map{ $0.id.uuidString })
center.removeDeliveredNotifications(withIdentifiers: toBeRemovedPushedItems.map{ $0.id.uuidString })
for item in toBePushedItems {
try await center.add(item.notificationRequest)
}
UIApplication.shared.applicationIconBadgeNumber = (await center.deliveredNotifications()).count
}
}
pushNotification
is called when app scenePhase
changes to .inactive
I plugged in @UIApplicationDelegateAdaptor(AppDelegate.self)
in the main SwiftUI App struct to log notification arrival and to show them when app is opened. Notification arrivals are logged correctly. The print(pushed)
and setting applicationIconBadgeNumber
expressions showed that the notifications sent do exist in notification center but they are not shown there. I tried it in both simulator and my iPhone and got the same unexpected behavior. How can I fix it?
More relevant code:
extension Item {
var notificationRequest: UNNotificationRequest {
let content = UNMutableNotificationContent()
content.title = "\(name ?? "(nil)") (\(type ?? "(nil)"))"
content.body = "Expiring on \(dateFormatter.string(from: date))"
// Tried both using and not using trigger
return UNNotificationRequest(identifier: id.uuidString, content: content, trigger: nil)
}
}
Upvotes: 0
Views: 100