Application badge number is not incrementing with local notification - ios

I have been working with local notifications. But the problem is the application icon badge number is not incrementing with local notifcations fired. I tried .applicationIconBadgeNumber+1;
But it's not giving any effect. The application icon badge number is always 1.
enter code here
- (IBAction)save:(id)sender
{
eventitem=textfield.text;
NSDate *newdate=self.datepick.date;
UIApplication *app=[UIApplication sharedApplication];
notifyalarm=[[UILocalNotification alloc]init];
if (notifyalarm)
{
notifyalarm.fireDate=newdate;
notifyalarm.timeZone=[NSTimeZone defaultTimeZone];
notifyalarm.alertBody=eventitem;
notifyalarm.applicationIconBadgeNumber=[UIApplication sharedApplication] .applicationIconBadgeNumber+1;
[app scheduleLocalNotification:notifyalarm];
}
}

UPDATE
After seeing your code I would suggest to use following before setting badge value
NSUserDefaults* userDefs = [NSUserDefaults standardUserDefaults];
//old val
NSInteger iconBadge = [userDefs integerForKey:#"myBadgeVal"];
//updatge val
iconBadge++;
//store
[userDefs setInteger:iconBadge forKey:#"myBadgeVal"];
[userDefs synchronize];
//set as icon badge
notifyalarm.applicationIconBadgeNumber=iconBadge;
However I'm not sure when 'save' method is called. Make sure this method is called as many times as you expect.
You have to handle locally this number, as [UIApplication sharedApplication] .applicationIconBadgeNumber will always be 0(as you do not update this value anywhere). You could use NSUserDefaults if you wish. Also please provide some code so we can be more helpful.

If your first Settled LocalNotification will fire first then you can use following way to set BadgeCount.
notifyalarm.applicationIconBadgeNumber = ([[[UIApplication sharedApplication] scheduledLocalNotifications] count] + 1);

Related

Repeating and canceling UILocalNotification

I want to have a UILocalNotification firing in my application every minute for a variable number of times and after that, I want to cancel it.
I'm trying to find a parameter that would enable me to do that.
1) Scheduling notification
Note the .repeatInterval property value.
UILocalNotification *reminder = UILocalNotification.new;
reminder.fireDate = fireDate;
reminder.timeZone = [NSTimeZone systemTimeZone];
reminder.alertBody = #"Your alert message";
reminder.alertAction = #"Your alert action";
reminder.soundName = UILocalNotificationDefaultSoundName;
reminder.repeatInterval = NSMinuteCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:reminder];
2) Handling notification (AppDelegate)
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
// custom handling code
}
Note: in iOS 8 you have to register for local notifications for the delegate methods to be called.
3) Canceling UILocalNnotification
[[UIApplication sharedApplication] cancelLocalNotification:reminder];
4) Notification distinction
To keep track of how many times a notification has been received, you have to uniquely identify your notification(s). You can do that by making use of UILocalNotification instance .userInfo property.
Example
UILocalNotification *reminder = UILocalNotification.new;
...
reminder.userInfo = [NSDictionary dictionaryWithObject:#"custom value" forKey:#"notificationUniqueId"];
...
Then, when you receive your notification in delegate method written in 2), you can check for notification unique id that you stated in userInfo dictionary. Knowing that, you are able to keep track how many times a UILocalNotification has been fired and cancel it when appropriate.
Hope that helps!

How to differentiate two uilocalnotification inside application didRecieveLocalNotification and fire corresponding alert in ios?

In my app i am scheduling two UILocalNotification,one is fired depending on the time selected in UIDatePicker and other on repeat Interval basis.The problem here is i have to fire two different alert for both when user tap on the notification.How can i distinguish these two notification and fire corresponding alert .
Part of the UILocalNotification object you will get there is a userInfo property. Set a key like "type" to values like "main" and "repeat" to differentiate the notification.
What do you mean by repeat interval basic. Are you talking about the notification for the snooze functionality. If that is the case then you dont have to set the second notification for repeat interval at the time of setting the original notification. You can set the repeat interval notification only when the original notification is fired.
Besides you can set the setUserInfo attribute of the notification object.
[localNotification setUserInfo:[[NSDictionary alloc] initWithObjectsAndKeys:#"Snoozed", kSnoozedAlarm, nil]];
You can give your notification a unique name in order to distinguish it from the others.
You can then iterate through the scheduledLocalNotifications to search for the specific notification.
NSArray *arrayNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
for (int i = 0; i < [arrayNotifications count]; i++)
{
UILocalNotification *snoozedNotification = [arrayNotifications objectAtIndex:i];
NSDictionary *userInfo = snoozedNotification.userInfo;
if ([[userInfo objectForKey:kSnoozedAlarm] isEqualToString:#"Snoozed"])
{
[[UIApplication sharedApplication] cancelLocalNotification:snoozedNotification];
}
}
You can use the below code in order to repeat the alert.
[localNotification setRepeatInterval:NSWeekCalendarUnit];

how to Count (track) Local notification in background mode?

I have a local notification which fire every minutes. I have done that part. But my problem is I want to count the notification and (count=15) then it's stop it. I can do that part in application running state. How can I achieve in background mode?
And also I want to track how many notification are fire? Is it possible in background mode.
//below is my notification delegate method
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
if (notification) {
// notification code goes here
}
}
Any demo code then appreciate. Thanks in advance.
You cannot really do that. Only way is to setup 15 notification in a row and keep your own list with dates. iOS is not giving you access to notification list or anything. What's more they don't have to be fired if user blocked them.
So I would advice to make own list with events + dates and manage them independently from notifications - especially when you have some important logic to be run based on that you cannot use notifications for that.
save your counter in the user defaults in didReceiveLocalNotification:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
int counter = [[userDefaults valueForKey:#"notiCounter"] intValue];
counter =+ 1;
if (counter == 15) {
} else {
[userDefaults setValue:[NSString stringWithFormat:#"%i",counter] forKey:#"notiCounter"];
[userDefaults synchronize];
}
of course you have to initialize the counter and store in didFinishLaunchingWithOptions.

Can I dismiss the local notification when next time the app launch?

I know I can cancel the notification when user tap this notification in notification center . But can I cancel the notification in other palce where I can't get the related local notification from system. Can I serialize the local notification, and cancel it when the app runs next time?
Sorry for make you misunderstand!
I want to dismiss a posted notification in the notification center, but not a scheduled one.
So what I want to ask is how to save the local notification object, then I can use it dismiss itself when next time the app launch. Maybe this job can't be done with current sdk.
If you need to cancel all notification you can use:
[[UIApplication sharedApplication] cancelAllLocalNotifications];
For cancelling a particular notification:
[[UIApplication sharedApplication] cancelLocalNotification:aNotification];
For getting the particular Notification you can use:
NSArray *notifArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
for (int i = 0; i < [notifArray count]; i++)
{
UILocalNotification *aEvent = [notifArray objectAtIndex:i];
NSDictionary *userInfo = aEvent.userInfo;
NSString *notifId=[NSString stringWithFormat:#"%#",[userInfo valueForKey:#"id"]];
if ([id isEqualToString:cancelId])
{
[[UIApplication sharedApplication] cancelLocalNotification:aEvent];
break;
}
}
Here:
You need to store a id key value pair in the userInfo of your notification for identifying particular local notification
cancelId is the id of notification which you want to cancel (Stored in user info)
If you save a link to your notification, then you will can cancel it before it fires.
[[UIApplication sharedApplication]cancelLocalNotification:yourNotification];
Use this Code to get all scheduled notifications:
NSArray *reminderArray=[[UIApplication sharedApplication]scheduledLocalNotifications];
Then you can select the notification required and delete it.
[[UIApplication sharedApplication]cancelLocalNotification:yourNotification];

Setting the application badge number to 0 is not clearing notifications [duplicate]

I've an iOS application where some Push Notification are sent to. My problem is, that the messages/notifications stays in the Notification Center in iOS after then are tapped. How can I remove a notification for my application in the Notification Center next time the application opens?
I came across posts where people are calling setApplicationIconBadgeNumber to a zero-value to clear the notifications. That's seems very weird to me, so I believe that maybe another solution exists?
EDIT1:
I'm having some problems clearing the notifications. Please see my code here:
- (void) clearNotifications {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (launchOptions != nil)
{
NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{
NSLog(#"Launched from push notification: %#", dictionary);
[self clearNotifications];
}
}
return YES;
}
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
NSLog(#"Received notification: %#", userInfo);
[self clearNotifications];
}
I'm running the App through Xcode. When the App is minimized and I start the App using the notification in the Notification Center, I can see in the log, that the didReceiveRemoteNotification is called and using breakpoints I can see, that the clearNotifications has ran. But still the notification hangs in the Notification Center. Why?
Most likely because Notification Center is a relatively new feature, Apple didn't necessarily want to push a whole new paradigm for clearing notifications. So instead, they multi-purposed [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0]; to clear said notifications. It might seem a bit weird, and Apple might provide a more intuitive way to do this in the future, but for the time being it's the official way.
Myself, I use this snippet:
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
which never fails to clear all of the app's notifications from Notification Center.
Just to expand on pcperini's answer. As he mentions you will need to add the following code to your application:didFinishLaunchingWithOptions: method;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
You Also need to increment then decrement the badge in your application:didReceiveRemoteNotification: method if you are trying to clear the message from the message centre so that when a user enters you app from pressing a notification the message centre will also clear, ie;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
It might also make sense to add a call to clearNotifications in applicationDidBecomeActive so that in case the application is in the background and comes back it will also clear the notifications.
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[self clearNotifications];
}
Update for iOS 10 (Swift 3)
In order to clear all local notifications in iOS 10 apps, you should use the following code:
import UserNotifications
...
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.removeAllPendingNotificationRequests() // To remove all pending notifications which are not delivered yet but scheduled.
center.removeAllDeliveredNotifications() // To remove all delivered notifications
} else {
UIApplication.shared.cancelAllLocalNotifications()
}
This code handles the clearing of local notifications for iOS 10.x and all preceding versions of iOS. You will need to import UserNotifications for the iOS 10.x code.
If you have pending scheduled local notifications and don't want to use cancelAllLocalNotifications to clear old ones in Notification Center, you can also do the following:
[UIApplication sharedApplication].scheduledLocalNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
It appears that if you set the scheduledLocalNotifications it clears the old ones in Notification Center, and by setting it to itself, you retain the pending local notifications.
If you're coming here wondering the opposite (as I was), this post may be for you.
I couldn't figure out why my notifications were clearing when I cleared the badge...I manually increment the badge and then want to clear it when the user enters the app. That's no reason to clear out the notification center, though; they may still want to see or act on those notifications.
Negative 1 does the trick, luckily:
[UIApplication sharedApplication].applicationIconBadgeNumber = -1;
In Swift I'm using the following code inside my AppDelegate:
func applicationDidBecomeActive(application: UIApplication) {
application.applicationIconBadgeNumber = 0
application.cancelAllLocalNotifications()
}
Maybe in case there are scheduled alarms and uncleared app icon badges.
NSArray *scheduledLocalNotifications = [application scheduledLocalNotifications];
NSInteger applicationIconBadgeNumber = [application applicationIconBadgeNumber];
[application cancelAllLocalNotifications];
[application setApplicationIconBadgeNumber:0];
for (UILocalNotification* scheduledLocalNotification in scheduledLocalNotifications) {
[application scheduleLocalNotification:scheduledLocalNotification];
}
[application setApplicationIconBadgeNumber:applicationIconBadgeNumber];
When you have repeated notifications at future, you do not want to cancel those notifications, you can clear the item in notification center by:
func clearNotificationCenter() {
UIApplication.sharedApplication().applicationIconBadgeNumber = 1
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
}
You cannot clear notification when your app is open in the foreground by calling the method below immediately after receiving local notification, otherwise you will receive tens of hundreds of notifications. Maybe because the same notification apply again, and now is the time to fire, so you keep fire, apply again, fire, apply....:
[UIApplication sharedApplication].scheduledLocalNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
When you logout from your app, at that time you have to use a below line of code on your logout button click method.
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
and this works perfectly in my app.
You need to add below code in your AppDelegate applicationDidBecomeActive method.
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
Got it from here. It works for iOS 9
UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
{
UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
//Cancelling local notification
[app cancelLocalNotification:oneEvent];
}

Resources