Apple push notification badge number - objective-c

I have developed server side application to maintain the badge number as increment or decrement after receiving new notification and delete after seeing notification it works fine.
But there is some problem in showing the badge, the actual scenario is - After getting new notification on device, I am click on cancel button then badge number shows correctly but after that I will open the application and close the application badge will be removed. That means I am not sending request to the server that notification was seen by me and now you can decrement the badge by one. Then also badge removed from app icon.
My question is that when we open the application then badge number automatically removed from (application) device? or it will shows as it is until we set to zero?

It will show until you set it to zero and you can do it with the following code:
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]
EDIT:
It is more common to set the badge number as you receive the notification, in either application:didReceiveRemoteNotification: or application:didFinishLaunchingWithOptions: methods of your UIApplicationDelegate class.
You can read more about it in the Local and Push Notification Programming Guide

If you want to change the icon badge automatically use the following code.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
application.applicationIconBadgeNumber = 0;
NSLog(#"userInfo %#",userInfo);
for (id key in userInfo) {
NSLog(#"key: %#, value: %#", key, [userInfo objectForKey:key]);
}
[application setApplicationIconBadgeNumber:[[[userInfo objectForKey:#"aps"] objectForKey:#"badge"] intValue]];
NSLog(#"Badge %d",[[[userInfo objectForKey:#"aps"] objectForKey:#"badge"] intValue]);
}
We also need to change the php file. So we can get the change the icon badge automatically
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'id' => '135',
'badge' => 8
);

Related

why isn't didReceiveRemoteNotification being fired in my react-native app?

I'm building a react-native app. Every time our cloud sends an APNS message, we want to increment the badge by 1.
I'm using the react-native PushNotificationIOS module to handle messages, but there's a known limitation with react-native, where the JS bridge is deactivated when the app is in the background. As a result, react-native application code that wants to manipulate the badge isn't executed, because the notification event is never delivered to the javascript.
It's important that this badge operation occur even when the app is not in the foreground, so I decided to implement the badge-incrementing logic in Objective-C, directly in AppDelegate.m. (Note: I don't understand ObjC, and can only loosely follow it.)
Here's the entirety of didReceiveRemoteNotification from AppDelegate.m:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification
{
// --- BEGIN CODE I ADDED --- //
// increment badge number; must be written in ObjC b/c react-native JS bridge is deactivated when app in background
NSLog(#"remote notification LINE 1");
NSUInteger currentBadgeNum = [UIApplication sharedApplication].applicationIconBadgeNumber;
NSLog(#"currentBadgeNum = %d", currentBadgeNum);
NSUInteger newBadgeNum = currentBadgeNum + 1; // to increment by .badge: ... + [[[notification objectForKey:#"aps"] objectForKey: #"badge"] intValue]
NSLog(#"newBadgeNum = %d", newBadgeNum);
[UIApplication sharedApplication].applicationIconBadgeNumber = newBadgeNum;
NSLog(#"done updating badge; now notifying react-native");
// --- END CODE I ADDED --- //
// forward notification on to react-native code
[RCTPushNotificationManager didReceiveRemoteNotification:notification];
}
When I test it, none of the log statements appear in Xcode when the app is backgrounded. However, when the app is active, the log statements appear and the routine works exactly as expected (and the notification is delivered to the javascript code as well).
I believe I've already configured the app to receive push-notifications; here's the relevant section from my Info.plist:
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
What am I missing? Is there a problem with my code, or am I misunderstanding the nature of didReceiveRemoteNotification?
Any help is appreciated.

token pushwoosh is nil

in my app a pushNotificationManager give me a pushToken equal nil... only with IOS 8.1.3.... device is ipad3. With other device (or with other IOS version) my test it's ok..
i used this code to call getPushToken...
[[PushNotificationManager pushManager] getPushToken]
and in my appDelegate I have
-(void) settingPushwoosh:(NSDictionary *)launchOptions {
// set custom delegate for push handling, in our case - view controller
PushNotificationManager * pushManager = [PushNotificationManager pushManager];
pushManager.delegate = self;
// handling push on app start
[[PushNotificationManager pushManager] handlePushReceived:launchOptions];
// make sure we count app open in Pushwoosh stats
[[PushNotificationManager pushManager] sendAppOpen];
// register for push notifications!
[[PushNotificationManager pushManager] registerForPushNotifications];
}
Do you receive delegate callback when push token received? Sometimes you need to wait a little as this is asynchronous operation.

Application icon badge number not increasing : Xcode

I am facing a problem with push notification application badge number value updation.
I am doing like:
-(void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
// do stuff when app is active
}else{
// do stuff when app is in background
[UIApplication sharedApplication].applicationIconBadgeNumber =
[UIApplication sharedApplication].applicationIconBadgeNumber+1;
/* to increment icon badge number */
}
}
But, the icon is showing the badge number as '1' always, and it is not incrementing when more notifications are there/ one notification came after another.
Any advice is appreciable...
The badge number is set by the operating system when you receive a JSON notification payload that resembles the following:
{
"aps" : {
"alert" : "New notification!",
"badge" : 2
}
}
As you see, it's the server who is responsible for setting the correct number in the badge key. Your server needs to track or compute the number of pending notifications for each user and generate the badge number before sending the notification to Apple.
The client responsibility is to clear the notification badge, or decrement it, when the user sees a notification. The code to do so is
application.applicationIconBadgeNumber = application.applicationIconBadgeNumber - 1; // Decrement counter
or
application.applicationIconBadgeNumber = 0; // Reset counter assuming the user is able to see all notifications at once.
you can create a static variable instead, and assign it to the applicationIconBadgeNumber:
static int i=1;
[UIApplication sharedApplication].applicationIconBadgeNumber = i++;
I had the same problem and solved it by creating int. variable in class.h
like this :
a custom class.H
#property int badge;
a custom class.M
-(id)init{
_badge=0;
self = [super init];
if (self) {
}
return self;}
-(void)reminderCreator:(NSDate*)onTime withText:(NSString*)text{
_badge += 1;
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = onTime;
localNotification.alertBody = text;
localNotification.soundName=UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber=_badge;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; }
so if you initialize this custom class, somewhere (maybe at your viewController) and then call the reminderCreator method several times to setup few localNotifications, it will assign incremented number to each notification.
+1 if this helped :)
The -(void)application:didReceiveRemoteNotification: will only be called when your app is running in the foreground.
If you want the badge to be increase when your app isn't running you should set the badge number in the push notification payload.
You should there for keep track of the badge number server side, since the badge property of the push notification payload will be use as the badge number. It will not increment the badge number for you.
Since the system handles the incoming push notifications your app is not informed of received push notifications for you app. Only when you app is running in foreground will the -(void)application:didReceiveRemoteNotification: be called. There is no way to get you app to repsond to push notification when it is not in the foreground.
Yes it seems that it always returns badgeNumber 1 in spite it has value increased to 2.
when using such code:
// update badge count
let currentBadgeCount = UIApplication.shared.applicationIconBadgeNumber
let badge = (aps["badge"] as? Int) ?? 1
UIApplication.shared.applicationIconBadgeNumber = currentBadgeCount + badge
so I think the only solution will be to store it in UserDefaults and then update value of UserDafaults and then it is set then update badge count?
This should work:
static var notificationsCount: Int {
set {
let userDefaults = UserDefaults(suiteName: SharedAppData.appGroup)
userDefaults?.set(newValue, forKey: "notificationsCount")
UIApplication.shared.applicationIconBadgeNumber = newValue
}
get {
let userDefaults = UserDefaults(suiteName: SharedAppData.appGroup)
return userDefaults?.integer(forKey: "notificationsCount") ?? 0
}
}
And then
SharedAppData.notificationsCount = 0 // to reset badge count
And this to increment
// update badge count
SharedAppData.notificationsCount += 1

How to set badges on app icon when app is in minimize mode?

When application is in minimize state and at the same time notifications come then badges should be see on app icon.
If a notification arrives and your application is not is foreground, the OS handles the notification.
Your notification can have a field badge that will make the OS update the badge. However, this means that the server than sends the notification must have a way of knowing which number should be the badge.
The notification body would look like this:
{
"aps" : {
"badge" : 9
}
}
Heres my solution. I needed to achieve the same thing in an app that I did. I had a queue of Downloads and wanted to use a Badge to show how many downloads were left, and keep updating it even while in the background. Basically my solution was, every time one of the downloads were completed I setup a UILocalNotification with a silent sound, and no message text. Simply just set the badge..As seen below..
- (void)queRequestFinished:(ASIHTTPRequest *)request {
self.inResourceCount -= 1; // Deducted 1 from the total count of downloads in queue.
Class cls = NSClassFromString(#"UILocalNotification");
if (cls != nil) {
UILocalNotification *notif = [[cls alloc] init];
notif.fireDate = [NSDate date]; // Schedule notification for now.
notif.timeZone = [NSTimeZone defaultTimeZone];
notif.soundName = #"silence.caf";
notif.applicationIconBadgeNumber = inResourceCount; // Number you want displayed as Badge.
// This is where the magic happens, and actually changes your badge.
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
[notif release];
}
}
Id like to point out, that my scenrio may be different from yours. I was using ASIHTTPRequest library, which has support for continuing downloads while backgrounded, and the method above queRequestFinished: is called even while in the background. Hope this helps, if it does mark it as the answer :) .

didReceiveRemoteNotification and Badge Number

Alright im a bit stuck on how to work this.
First ill show you the code.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
}
sorry for the abundance of mess, the Code button was not working.
Now my push gateway provides a number each time for how many alerts are being sent, etc, but if there are previous alerts, how would i get this code to just add +1 to the list instead of just setting the new number
APNS doesn't support increment operations for badges; each push notification generated should be setting what the current value should be. (Mainly due to the fact that push notifications aren't guaranteed to be received by a device)
So, you'll need to have a service/server somewhere keeping track of what badges should be for each of your users, unfortunately.
You should try this:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
int currentBadgeNumber = application.applicationIconBadgeNumber;
currentBadgeNumber += [[apsInfo objectForKey:#"badge"] integerValue];
application.applicationIconBadgeNumber = currentBadgeNumber;
}