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

后端 未结 2 915
自闭症患者
自闭症患者 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.

提交回复
热议问题