UNUserNotificationCenter.current().getDeliveredNotifications only ever returns an empty array

后端 未结 2 972
自闭症患者
自闭症患者 2021-02-20 16:49

Basically, I\'m simply trying to print the notifications that my app has delivered, but doing something like:

UNUserNotificationCenter.current().getDeliveredNoti         


        
相关标签:
2条回答
  • 2021-02-20 17:33

    It was empty when I used it on a UNNotificationServiceExtension, it turned out that I needed to use a Semaphore in order to prevent the extension to return 0 results:

            let semaphore = DispatchSemaphore(value: 0)
            let center = UNUserNotificationCenter.current()
            center.getDeliveredNotifications { notifications in
                defer {
                    semaphore.signal()
                }
    
                let relatedNotificationIdentifiers = notifications.filter { notification in
                    notification.request.content.userInfo["callId"] as? String == callId
                        && notification.request.identifier != request.identifier
                }.map(\.request.identifier)
    
                // This call is async
                center.removeDeliveredNotifications(withIdentifiers: relatedNotificationIdentifiers)
    
                // ...so this call needs to be done with a slight delay because otherwise
                // it will be killed before it is done removing the notifications
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                    contentHandler(bestAttemptContent)
                }
            }
    
            semaphore.wait()
    

    Also, in the end it needed some wait to execute removeDeliveredNotifications which is async under the hood as well.

    apns-collapse-id can help reducing incoming APNS messages.

    0 讨论(0)
  • 2021-02-20 17:49

    I did face the same problem with getDeliveredNotification, the array of notifications were always empty.

    So, I realized that I was setting [UIApplication sharedApplication].applicationBadgeNumber to 0, what clear all remote notifications from notification center.

    Now I set applicationBadgeNumber to 0 only after I get all pending notifications.

    0 讨论(0)
提交回复
热议问题