UNNotificationServiceExtension and App Badge Number


I have an app that uses CloudKit and notifications. I write information to a AppNotification record that includes information about the notification like if it has been viewed in the app. I have a subscription on the AppNotification record based on the user ID which creates the notification. I also have a UNNotificationServiceExtension that modifies the notification payload.


Everything works fine except for when I get a notification when the app is in the background. In the UNNotificationServiceExtension I don't know how to properly set the bestAttemptContent.badge to be the number of unviewed AppNotification records for that users. In addition, CloudKit seems to have a count of unviewed notifications that don't match the count for my AppNotification records, and is much night because I don't ever do anything with it.


Here is what I have tried to get the badge count correct:


1) Count the unviewed AppNotification records in UNNotificationServiceExtension

In the UNNotificationServiceExtension I can read the number of unviewed AppNotification records for the user and then set bestAttemptContent.badge. The problem with this is that I get either the correct count or the correct count -1. It seems like this is because the write of the AppNotification is eventually consistent, and it's not always there. I would have thought that if I wrote an AppNotificaiton record that CloudKit would not send a notification until the record was written, but that doesn't appear to be the case.


2) Increment the current badge

In UNNotificationServiceExtension I could just increment the current app badge count by 1. But, since the UNNotificationServiceExtension doesn't run a part of the app I don't see any way to get the current app badge count.


3) Use the CloudKit unviewed notification count

I've read the documentation multiple times and I don't really understand this. I don't see how to get a count or modify the count from CloudKit that isn't deprecated. I also don't see how to correlate the CloudKit notification with my AppNotification records. This sounds like the correct way to do this so the CloudKit counts matches the true unread count of AppNotification records.


Is there a way to set the bestAttemptContent.badge in the UNNotificationServiceExtension so it matches the unviewed AppNotification count? Is there a better way to do this?

I found a way to do what I need to do. Since the app has the current unviewed AppNotification count, I set up an app group and had the app set the value to the user defaults and then the notification service extension could read that value from the user defaults.

UNNotificationServiceExtension and App Badge Number
 
 
Q