How to Remove Push Notification in Notification Ce

2019-04-22 10:07发布

问题:

Is there any way to handle the push notification from the Notification Center after being tap, and remove it when my application has already launched?

回答1:

I know this is hack and slash, but you can clear all notifications by changing the badge number on your application.

- (void)application:(UIApplication*)application didReceiveRemoteNotification (NSDictionary*)payload
{
    NSLog(@"Received notification: %@", payload);
    //swapping between two badge numbers to clear notifications
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    ...
}

If you already had a badge number you don't want to lose (above example will simply clear badge number in the end) you can do something like

- (void)application:(UIApplication*)application didReceiveRemoteNotification (NSDictionary*)payload
{
    NSLog(@"Received notification: %@", payload);
    /*
     storing current badge number then swapping between 2 values to make sure we 
     clear the badge number. Once this is done set badge number back to original 
     value.
    */
    int badgeNum = [[UIApplication sharedApplication] applicationIconBadgeNumber]
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badgeNum];
    ...
}

This may not be best practice, but it gets the job done and the client will not know the difference. I like to call it a temp. fix until I stumble upon a better solution. Hope this helps someone!