Peter Warbo Peter Warbo - 5 months ago 50
iOS Question

UILocalNotification app badge number on repeat

I'm using

UILocalNotification
s in my app. Sometimes I schedule a repeating notification and sometimes a non-repeating notification. Whenever a notification fires I want to increment the app badge number. So I do
localNotification.applicationIconBadgeNumber = badgeNumber;
this works fine... except when the notification is a repeating notification because if I have previously set a repeating notification with badge number 1, then I set another non-repeating notification with badge number 2.

Flow is this:

Notification 1 fires (first time) - Badge number = 1 (OK!)
Notification 2 fires - Badge number = 2 (OK!)
Notification 1 fires (repeating) - Badge number = 1 (ERROR)


As you understand when notification 1 fires again I still want the app badge number to be displaying 2 (for 2 missed notifications). Can I possibly achieve this behaviour? Or is there something obvious that I have missed? For me the more logical badge behaviour for a repeating notification would be that it for the first time sets the badge number and for subsequent times it will not change the badge number.

Answer

I suppose the only way to deal with having repeated notifications and also have it increment the app badge number the first time it's fired is to schedule your repated notification without badge number like:

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:60];
localNotification.alertBody = @"1";
localNotification.alertAction = @"Send";
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSMinuteCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

And then schedule a notification which only sets the app badge number at the same time the repeated notification is fired for the first time:

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:60];
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = 1;
localNotification.hasAction = NO;
localNotification.alertBody = nil;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];