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.:
{
"aps": {
"content-available": 1,
"alert": "Hallo, this is a Test.",
"badge": 2,
"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.
{
"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")
let state = application.applicationState
switch state {
case .inactive:
print("Inactive")
case .background:
print("Background")
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) {
application.applicationIconBadgeNumber = 0
}