How to reset the Badge app icon number? - ios

I integrated the Push Notification to the CloudKit so that every change in the iCloud will pop up a notification on my iPhone and the badge app icon number will add one correspondingly. However, when I used the code:
application.applicationIconBadgeNumber = 0
to reset that number in the applicationDidBecomeActive(_ application: UIApplication), I noticed that the badge app icon number truly disappeared but if another new notification came again, the number won't start from one again as supposed but just add one to the original total number before the reset. Therefore the number is getting bigger and bigger. I wonder how to solve this problem?

The problem is your apns payload, it contains badge count more than 1, you need to reset the payload as well.
When you set application.applicationIconBadgeNumber = 0 it just resets the badge count locally, not in the server.
Solution would be reset the badge count for the user in the server too.
Update: Apns Payload
{
"aps" : {
"alert" : {
"title" : "Push",
"body" : "Hello User"
},
"badge" : 5
}
}
The app shows the badge count same as in the apns payload above, you need to reset the badge value in the payload above from server.
Hope it helps.
Cheers.

I find that I should not only set the application side like:
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
but I should also set the iCloud side in CKContainer. Therefore, the complete code is like below:
let operation = CKModifyBadgeOperation(badgeValue: 0)
operation.modifyBadgeCompletionBlock = {(error) in
if let error = error{
print("\(error)")
return
}
application.applicationIconBadgeNumber = 0
}
CKContainer.default().add(operation)

Related

How to reset badge number for app icon using Firebase cloud function notification payload?

Current behaviour: UserA send another userB message, notification is triggered while app is in background, the badge number increases as more messages trigger notification. UserB opens notification, the badge value is set to 0 and minimize the app. User A send another message to userB while userB app in background, the badge value is not reset to 1, instead, it continues from the last accumulated value.
Desired Behaviour: Have badge value increment from 1 when userB receives new notifications instead of incrementing from last accumulated notification badge value.
Further: I have checked the firebase payload, it seems like the payload is sending the accumulated value and not resetting the value after userB already set the value to 0 client side.
Cloud function below:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var badgeCount = 1;
exports.sendNotification = functions.database.ref('/Notifications/Messages/{pushId}').onWrite((change,context) => {
console.log('Push notification event triggered for testing');
console.log(change);
const message = change.after.val();
const senderUid = message.Sender;
const receiverUid = message.SendTo;
const chatMessage = message.Message;
const senderName = message.SenderName;
console.log(receiverUid);
const promises = [];
console.log('notifying ' + receiverUid + ' about ' + chatMessage + ' from ' + senderUid);
const payload = {
notification: {
title: senderName,
body: chatMessage,
badge: badgeCount.toString(),
sound: "default"
}
};
badgeCount++;
return admin
.database()
.ref("fcmToken").child(receiverUid)
.once("value")
.then(allToken => {
if (allToken.val()) {
const token = Object.keys(allToken.val());
console.log(`token? ${token}`);
return admin
.messaging()
.sendToDevice(token, payload)
.then(response => {
return null;
});
}
return null;
});
});
Inside project appDelegate applicationDidBecomeActive and applicationWillEnterForeground.
UIApplication.shared.applicationIconBadgeNumber = 0
While in the app, didbecomeactive I use UIApplication.shared.applicationIconBadgeNumber = 0 to reset it to 0 upon opening the app.
This is fine to reset badge counter. but,
However, the next time the notification is sent, the badge value starts at the previous incremented value again, e.g(5) instead of 1. Can someone explain/help what is going on here?
Here, you can not update badge counter from app side when push notification received.
iOS automatically update badge counter on app icon when push notification received with value of "badge" parameter of push notification payload. so, currently, you seems to send same value for "badge" in all notifications. so, if you send "badge" value "5". every time, badge value will be updated as "5".
so, you need to send proper badge value in notification payload from firebase function.
you may refer this google documentation for more details about "badge" parameter.: https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support
Three parts to solving your issue given firebase
1.) Create a field mapped to the specific user in your db that tracks the notification count.
2.) Implement logic on the client to update the notification field in the db based on the users actions
3.) Handle updating the badge number on the client

Push notifications disappear instantly

Is there any reason why a push notification would appear on the lock screen and then instantly disappear? I am using the didReceiveRemoteNotification block to save data in the notification.
Is it possible that your completionHandler code is setting the number of notifications to 0 ? That would make it disappear.
Either you put the number of notifications to 0 in your code like
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
Or in you Notification payload, you have a the badge property set to 0
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 0,
"sound" : "bingbong.aiff"
},
}

How to increase badge number when sending a parse push notification

I am having troubles increasing the badge number using the Parse iOS Framework.
When I call this code, the other user gets the Push notification, but his badge number is not increasing on the icon.
let push = PFPush()
let data = ["badge": "Increment"]
push.setData(data)
push.setChannel("channel_\(userId)")
push.setMessage(message)
var err: NSError?
do {
try push.sendPush()
} catch var error as NSError {
err = error
} catch {
fatalError()
}
Thanks!
Try with this in swift for increase
let currentCountStr = UIApplication.sharedApplication().applicationIconBadgeNumber.description
let currentCount = Int(currentCountStr)
if(currentCount > 0) {
UIApplication.sharedApplication().applicationIconBadgeNumber = currentCount! + 1
} else {
UIApplication.sharedApplication().applicationIconBadgeNumber = 1
}
You should check your database and/or code if you successfully updated 'Installation' table. The way it works is, that they store badge number in that table (perhaps refresh after each application is awaken) so later server can send incremented number inside notification payload.
Parse had a blog entry on this : http://blog.parse.com/announcements/badge-management-for-ios/
Just to add note how it works in more generic environment :
You should send actual new badge number from the server, it is not just incremented for you.
There is good deal of information on another question :
Increment the Push notification Badge iPhone

Update badge counter in Swift

With following code I get (2) in the badge icon immediately after app compiling:
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.badge = 2
installation.saveInBackground()
}
I did try the next variant: Initialized a new var badgeCount = 0 and later:
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
badgeCount++
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.badge = badgeCount
installation.saveInBackground()
}
But when I get new notifications it doesn't update to +1. Is anyone know how to fix it?
Whenever code is compiled it shows the badge icon which is previously store in your app. If you don't set the badge icon = 0 in your app it will show the badge icon number in your app every time you compile it or enter in background state.
Now for your problem, use badge icon as
var badgeCount = 0
UIApplication.sharedApplication().applicationIconBadgeNumber = ++badgeCount
Also whenever you are done with your task make badge icon as 0 otherwise it will show a badge icon in your app
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
It won't update the badge number with this method unless the app is actually open. If you want to update the badge number upon receiving a notification then you need to set the Badge property of the json push notification to the desired number.
If you, if you are sending a normal message (not using json) there is a toggle to increment the badge number, just tick that. If you're using Json then use this:
{
"aps": {
"alert": "Test Push Notification",
"sound": "yourSound.aiff",
"Badge": "desiredNumber"
}
}
Please note, if you do not wish to send this from the server, you can also send it from one device to another utilising Parse's client push, go into your settings in the app on Parse.com and enable "client push", you can then send the above Json to another user's device.
In Swift 5, you can update de application's badge whenever you want, using this code:
UIApplication.shared.applicationIconBadgeNumber = 0 // YOUR NUMBER DESIRED
I have worked on similar scenario and the final solution I found to increment and reset the badge numbers.
Increment Badge number
I always save the badge number count in the memory (NSUserDefaults)
Every time i have to set the notification, I get the current badge number increment that and set that number on .applicationIconBadgeNumber and update the count in memory.
Reset Badge Number
In my case, I have to reset all the badge count once the application is opened. So I have set UIApplication.sharedApplication().applicationIconBadgeNumber = 0 in didFinishLaunchingWithOptions of AppDelegate. Also I reset the count in the memory.
None of these answers are valid anymore.
You need to be looking at your Push code, not your AppDelegate
From the Parse docs:
badge: (iOS/OS X only)
the value indicated in the top right corner of the app icon.
This can be set to a value or to Increment in order to increment the current value by 1.

Update Badge count of app icon according to unread message in ios

I need the count value of unread as badge number.and badge number of app icon has to reduced and increase according to the unread message count.(increase if new unread message ,reduced if unread message is read)
->["Unread" is the count of unread messages.]
NSString *unread =[[NSUserDefaults standardUserDefaults]valueForKey:#"unread"];
int badge = [unread intValue];
[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge];
Usually the badge number is set by the OS when you receive JSON in the form of:
{
"aps" : {
"alert" : "New notification!",
"badge" : 2
}
}
So the server sets the badge number, meaning that you have to keep track of how many notifications a user has.
On the client side, you have to clear the notification like this:
application.applicationIconBadgeNumber = application.applicationIconBadgeNumber - 1; // Decrement counter
Or you can just set them all to 0 and assume they're all read once app is opened, like this:
application.applicationIconBadgeNumber = 0;

Resources