While there is no simple applicationIconBadgeNumber++
method as mentioned in BFar, you can achieve what you request by updating all the planned iIconBadgeNumber application identifiers for UILocalNotifications when a notification is added or removed.
While this will not work, if you have notifications that use repeatInterval
, while you call scheduleNotification
and decrementBadgeNumber
at the right time, the class below should do the trick.
@implementation NotificationScheduler + (void) scheduleNotification:(NSString*)message date:(NSDate*)date { UIApplication *app = [UIApplication sharedApplication]; UILocalNotification *notification = [[UILocalNotification alloc] init]; if (notification) { notification.fireDate = date; notification.timeZone = [NSTimeZone defaultTimeZone]; notification.alertBody = message; notification.soundName = UILocalNotificationDefaultSoundName; notification.applicationIconBadgeNumber = [self getExpectedApplicationIconBadgeNumber:date]; [app scheduleLocalNotification:notification]; [self updateBadgeCountsForQueuedNotifiations]; } } + (void) decrementBadgeNumber:(long)amount { [self setCurrentBadgeNumber:([self getCurrentBadgeNumber] - amount)]; [self updateBadgeCountsForQueuedNotifiations]; } + (long) getExpectedApplicationIconBadgeNumber:(NSDate*)notificationDate { long number = [self getCurrentBadgeNumber]; for (UILocalNotification *notice in [self getScheduledLocalNotifications]) { if (notice.fireDate <= notificationDate) { number++; } } return number; } + (void) updateBadgeCountsForScheduledNotifiations { long expectedBadgeNumber = [self getCurrentBadgeNumber]; NSArray *allLocalNotifications = [self getScheduledLocalNotifications]; for (UILocalNotification *notice in allLocalNotifications) { expectedBadgeNumber++; notice.applicationIconBadgeNumber = expectedBadgeNumber; } [[UIApplication sharedApplication] setScheduledLocalNotifications:allLocalNotifications]; } + (long) getCurrentBadgeNumber { return [UIApplication sharedApplication].applicationIconBadgeNumber; } + (void) setCurrentBadgeNumber:(long)number { [UIApplication sharedApplication].applicationIconBadgeNumber = number; } + (NSArray*) getScheduledLocalNotifications { NSSortDescriptor * fireDateDesc = [NSSortDescriptor sortDescriptorWithKey:@"fireDate" ascending:YES]; return [[[UIApplication sharedApplication] scheduledLocalNotifications] sortedArrayUsingDescriptors:@[fireDateDesc]]; } @end
source share