Update badge with push notification while app in background
Since push notification are handled by iOS and not your app you can't change the application badge on receiving a push notification.
But you can send the badge number in the payload of the push notification, but the you will have to do the calculation server side.
You should read Local and Push Notification Programming Guide and especially the The Notification Payload.
The payload could look like this:
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9
}
}
Now the app application badge icon will show 9.
Actually in iOS 10 a remote Notification will call automatically didReceiveRemoteNotification
Method in your AppDelegate.
You have 2 ways of updating the badge count in the background.
I've done this for my current app also. You don't need a Notification Service Extension either.
1st Way:
Send APS badge key with your payload to APN.
This will update the badge count according to your Integer value in your payload of badge. e.x.:
// Payload for remote Notification to APN
{
"aps": {
"content-available": 1,
"alert": "Hallo, this is a Test.",
"badge": 2, // This is your Int which will appear as badge number,
"sound": default
}
}
2nd Way:
You can switch your application.applicationState and update your badges Count when the applicationState is in .background
. BUT you have to take care not to set the badge key parameter in your Notification payload when sending to APN e.x.
// Payload to APN as silent push notification
{
"aps": {
"content-available": 1
}
}
Handle the badge Update accordingly to the application state:
Here is my working code for badge count update without badge key in the payload for APN.
func application(_ application: UIApplication, didReceiveRemoteNotification
userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("APN recieved")
// print(userInfo)
let state = application.applicationState
switch state {
case .inactive:
print("Inactive")
case .background:
print("Background")
// update badge count here
application.applicationIconBadgeNumber = application.applicationIconBadgeNumber + 1
case .active:
print("Active")
}
}
Reset badge count:
Don't forget to reset your badge count when your app gets back to active state.
func applicationDidBecomeActive(_ application: UIApplication) {
// reset badge count
application.applicationIconBadgeNumber = 0
}