APNS Background handling for badge counter - ios

I am integrated APNS in my app, The requirement is to maintain notification count when app in background. For example we got notification in background in there is key counter count , i,e changing dynamic in every notification, Can it possible to handle in iOS when app is background or app has forcefully closed.

This is the APNS payload from back end server.
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9,
"sound" : "bingbong.aiff"
},
"acme1" : "bar",
"acme2" : 42
}
The value for key badge is automatically considered as badge count.On ios app side no need to calculate or handle the count.
In above example 9 is the badge count.So your app icon will show 9.
NOTE While your app is close u can't handle badges on your own.Thats why we are using badge key from APNS Payload
For better clarification about notification see documentation
EDIT: if you want to reduce the badge count on your own.Decrement the count and update it yourself.as follows
NSInteger numberOfBadges = [UIApplication sharedApplication].applicationIconBadgeNumber
numberOfBadges -=1;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:numberOfBadges];
or else make the count to 0, so that badge icon will be disappeared.Add the below code in ** applicationDidBecomeActive**
application.applicationIconBadgeNumber = 0;

For managing the notification counter you have to setup functionality at server. lets take Facebook example if you are not reading the new notification the counter keep increase by one and once you click on notification it comes back to zero. so whenever you read new notification it also managed on server side whether is user opened it or not.
lets say there are 3 notifications user di't see than for next one counter will be 4.
And once your receive the count from server with update, handle it like if all updates are viewed application badge counter set to 0
this is my understanding as i have implemented the same in my iOS application if anyone has any good solution. please suggest.
I hope this picture(source google) will give the complete understanding.

Related

Cordova Push notifitication badge not displaying on app icon iOS

I am using cordova push plugin where I am getting notification and all data I needed, but also I want to set badge as per the unread notification or the number i am getting into count of push notification but I am not sure why I am not getting this count as a badge into app icon of iOS device
Here is the json format I am getting into push notification success function
{
"count":"1",
"sound":"default",
"additionalData":{
"foreground":true,
"product_id":"19",
"user_id":"2",
"coldstart":false,
"notificationstatus":"like"
},
"message":"Username likes your product"
}
Sound and message both were working perfect but not count.
Any suggestion ?
I noticed that, there is a string value of count in the response, and it was the mistake.
Count value must be an integer.
Hope this will help others too.
what you receiving is ok but one key is wrong. the key count should be badge. This is the problem i think. Try to change the key and reply the result.
reference - https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html

Reset count on icon badge

I send pushes using Parse.com. When i send pushes i set increment badge to "yes" so users can see badges with "1" on my app icon.
When users opens app's main ViewController, app clears badge count using this code
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
This works fine and badge is clear. But when i send new push with badge increment enabled - i see that number on badge is 2. Is something wrong with my way to reset badge count?
That's because while you remove the local badge, the badge count in Parse Installation class for that device remains the same. You can do the following to remove that:
Assuming that you have already made sure that current user has a PFInstallation (i.e. he did not decline the push notification access request) , To reset the badge number on backend, you can use the following:
var currentInstallation = PFInstallation.currentInstallation()
if currentInstallation.badge != 0 {
currentInstallation.badge = 0
currentInstallation.save
}
This makes sure to set the badge to 0 only if it is currently showing a non-zero counter.
Setting badge on currentInstallation will automatically set applicationIconBadgeNumber too. By doing this, Parse will know what number your app is currently displaying and they can increment the counter correctly whenever an Increment is sent to this device again. For more information you can read Official Parse Blog Announcement on this matter.

iOS 8 Beta 6 - Handling a UILocalNotification when the app is in Background

I'm creating an app for creating alarms. If the app isn't in background or inactive everything work fine. But if the app is inactive (because i've pressed home button or i've pressed the lock button) when the notification occurs, after sliding or touching the banner, the code isn't executed and the app doesn't complete its actions.
I've read a lot of topics here and on the web but nothing can help me. Documentation says:
In iOS, you can determine whether an application is launched as a result of the user tapping the action button or whether the notification was delivered to the already-running application by examining the application state. In the delegate’s implementation of the application:didReceiveRemoteNotification: or application:didReceiveLocalNotification: method, get the value of the applicationState property and evaluate it. If the value is UIApplicationStateInactive, the user tapped the action button; if the value is UIApplicationStateActive, the application was frontmost when it received the notification.
But application:didReceiveLocalNotification: method seems not to be called after sliding or tapping the notification. This method isn't called when a notification occurs and the app is inactive. How can execute the code for notification handling if app is inactive?
this is my code:
func application(application: UIApplication!, didReceiveLocalNotification notification: UILocalNotification!)
{
if(UIApplication.sharedApplication().applicationState == UIApplicationState.Active)
{
.
println("Notification recieved and handled when inactive")
.
}
.
.
.
}
All this code isn't executed when my application is in background or inactive or in lockscreen with my app still "alive" (when i push lock-screen button when my app is in foreground ). How can i handle Local Notification in these conditions? How can i recognize if the app is becoming active because of local notification occurs? I've found no solution to this problem.
two cases:
1 . when your app is not running, only applicationDidFinishLaunching is called.
(either never was or was killed)
In that case, the launchOptions NSDictionary contain the UIApplicationLaunchOptionsLocalNotificationKey key
2 . if it is running -regardless of the state- didReceiveLocalNotification is called
In that case, use UIApplication.sharedApplication().applicationState to see where your app is
note: with ios8 there is more to do for this to work
You need to implement with your use cases, wake up your notifications here
. It will notify your app when it is in background and there is scheduled local notification time to get up..
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
On iOS, when the app is suspended because, for example, you pressed the lock button, you need to change the notification priority to "high".
Here is a test code snippet that I've used before:
from gcm import GCM
import time
gcm = GCM('iOS Application ID issued by Google')
notification_topic = 'topic_name'
notification_text = '{"ticker": "XD", "company_name": "Vulchiany Technologies", "buy_target": "89.55", "profit_sell": "89.99", "loss_sell": "89.11", "alert_time": "' + time.strftime("%b %d, %Y %I:%M %p")+'"}'
for j in range(1,8):
for i in range(1, 11):
gcm.send_topic_message(topic=notification_topic, priority="high", notification={"body": "XD: Buy Target: $89.55", "title" : "Alert"}, data={'message': notification_text})
time.sleep(3)
print(notification_text)
print('Notification sent on ', time.strftime("%b %d %Y %I:%M %p"))
time.sleep(3600)

Can I get badge number with trigger.io

Trigger.io provides a forge.notification.setBadgeNumber method to set the ios badge number. Is it possible to retrieve the badge number with trigger.io?
My use case is that I have a messaging system where the badge number is the number of unread message - I want to decrease the badge number when the user reads a message. To do that, I need to know the current badge number...
Suggestion on better ways to implement this will also be appreciated.
You could easily write your own native module to get the current badge count in Trigger.io apps. I have one in use and the relevant function looks like this:
+ (void)getBadgeNumber:(ForgeTask*)task {
NSNumber *count = [NSNumber numberWithInt:[[UIApplication sharedApplication] applicationIconBadgeNumber]];
[task success:count];
}
UPDATE:
It seems like Trigger.io added the getBadgeNumber call to their notifications module. Available methods are:
forge.notification.setBadgeNumber(number, success, error)
forge.notification.getBadgeNumber(success, error)
If you're using the Parse module for push notifications you can even retrieve and set the badge number on the Parse server as of now.

Good pattern for UILocalNotifications and applicationIconBadgeNumber

My app schedules UILocalNotifications to be delivered to its users at varying times of the user's choice.
I'm running into a situation with how to manage the applicationIconBadgeNumber in this scenario.
As we know, you have to set the badge number at the time you create the notification. My problem is that the state of the number of badges can change at any time. Consider this scenario:
1) User gets 3 notifications.
2) User creates a new notification to alert her at a given point of time in the future. This notification carries the value of 1 plus the current value of the application badge (3).
3) User goes about their business. In the process of their business, they clear all 3 notifications (and, thus, badge numbers) they currently have by viewing them or otherwise using the app.
4) After the given amount of time passes, the notification appears in iOS, along with its previously calculated value (4, if you don't remember).
5) The application badge is now, 4 even though the user only has one actual notification.
I have searched up and down, but I cannot find an answer to this question which almost certainly has a simple answer I'm completely missing. How do I solve this quandary?
Since your app cannot look in the future, and know which events you'll handle immediately, and which ones you'll leave 'pending' for a while, there's some trick to do :
When notifications are handled by your app (by tapping on the notification(s), icon, ...), you have to :
get a copy of all pending notifications
'renumber' the badge number of these pending notifications
delete all pending notifications
re-register the copy of the notifications with their corrected badge
numbers again
Also, when your app registers a new notification, it has to check how many notifications are pending first, and register the new notification with with :
badgeNbr = nbrOfPendingNotifications + 1;
Looking at my code, it will get clearer. I tested this, and it's definitely working :
In your 'registerLocalNotification' method you should do this :
NSUInteger nextBadgeNumber = [[[UIApplication sharedApplication] scheduledLocalNotifications] count] + 1;
localNotification.applicationIconBadgeNumber = nextBadgeNumber;
When you handle the notification (appDelegate), you should call the method below, which clears the badge on the icon and renumbers the badges for pending notifications (if there are any)
Note that the next code works fine for 'sequential' registered events. If you would 'add' events in between pending ones, you'll have to 're-sort' these events first. I didn't go that far, but I think it's possible.
- (void)renumberBadgesOfPendingNotifications
{
// clear the badge on the icon
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
// first get a copy of all pending notifications (unfortunately you cannot 'modify' a pending notification)
NSArray *pendingNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
// if there are any pending notifications -> adjust their badge number
if (pendingNotifications.count != 0)
{
// clear all pending notifications
[[UIApplication sharedApplication] cancelAllLocalNotifications];
// the for loop will 'restore' the pending notifications, but with corrected badge numbers
// note : a more advanced method could 'sort' the notifications first !!!
NSUInteger badgeNbr = 1;
for (UILocalNotification *notification in pendingNotifications)
{
// modify the badgeNumber
notification.applicationIconBadgeNumber = badgeNbr++;
// schedule 'again'
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
}
}
Credits to #Whassaahh

Resources