Jacob Jacob - 5 months ago 15
iOS Question

Clear Banner Notification When Tapped

I have noticed that when I select a push notification for my app from notification center, that notification no longer appears in the list of notifications. However, when I receive a notification and tap the banner right away, the app opens as it should, but when I pull down to view the notification center, that notification is still there. I have the following push handling code in my delegate:

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {

[[UIApplication sharedApplication] cancelAllLocalNotifications];

//Presenting view controllers...

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.


// Extract the notification data
NSDictionary *notificationPayload = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];

if(notificationPayload)
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];

}
return YES;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
application.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{

// when you tap on any of notification this delegate method will call...
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
[[UIApplication sharedApplication] cancelLocalNotification:notification];

}

Answer

You have to use following to remove all notifications

 - (void)applicationWillEnterForeground:(UIApplication *)application
    {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
        [self clearnotifications];

    } 

- (void)applicationDidBecomeActive:(UIApplication *)application
    {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
        [self clearnotifications];

    }

-(void)clearnotifications
    {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    }