I was like you and I could not see straight answer other than "do it on the server."
Here my way:
1) You need to set badge ( a variable you can call it whatever you want) to zero into Firebase Realtime database once you launch the app. Plus set application.applicationIconBadgeNumber = 0. Here is how I do it in AppDelegate:
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
application.applicationIconBadgeNumber = 0
// Reset badge number to zero
let userID = Auth.auth().currentUser?.uid
let dbRef = Database.database().reference()
dbRef.child("Users Info").child(userID!).updateChildValues(["badge":"0"], withCompletionBlock: { (err, ref) in
if err != nil {
print(err!)
return
}
})
}
2) Go to index.js where a function is triggered.
...
return admin.database().ref('/Users Info/' + owner).once('value', snapshot => {
var ownerValue = snapshot.val();
var badgeNumber = parseInt(ownerValue.badge) + 1;
// Notification details.
const payload = {
notification: {
title: 'You have a new request!',
body: `A new request from ${downedBy.name}.`,
badge:`${badgeNumber}`,
sound: 'default',
}
};
...
...
// Upload the new value of badge into Firebase to keep track of the number
return admin.database().ref('/Users Info/' + owner).update({badge:badgeNumber});
...
})