UIApplication scheduledLocalNotifications is empty

2019-04-10 22:49发布

问题:

I have tried out the 3do app which seems to be able to schedule non-repeating notifications and have specific notifications from notification center deleted. It works as this: when app is in background they are delivered in notification center, if you choose one of these notifications 3do will open and you have the option to tap "done", if you tap "done" that specific notification will be removed from the notification center. If you don't tap anything the notification will be left in notification center.

This is the problem I am myself having in one of my own applications, I can't understand how to delete an individual notification from the notification center. If the notification does not have a repeat interval then the scheduledLocalNotifications array of UIApplication will be empty so I can't cancel that specific notification and have it removed from the notification center. However if the notification has a repeat interval the scheduledLocalNotifications array will not be empty and I can delete this notification. But how can I deal with the scenario when the notifications are non-repeating?

回答1:

scheduledLocalNotifications array will show as empty even if you have set local notifications. Best way is to keep individual local notification objects. So that you can easily delete it.

When you set local Notification, save the object like this

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

NSString *userDefKey =  @"key";
NSData *dataEnc = [NSKeyedArchiver archivedDataWithRootObject:localNotification];
[[NSUserDefaults standardUserDefaults] setObject:dataEnc forKey:userDefKey];

You should keep the key

When you want to delete a specific local notification

if([[NSUserDefaults standardUserDefaults] objectForKey:userDefKey]){

    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:userDefKey];
    UILocalNotification *localNotif = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    [[UIApplication sharedApplication] cancelLocalNotification:localNotif];

}


回答2:

Harikrishnan got me on right track, but I think there is actually an even better solution for this which is dead simple.

In the - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification you will have a reference to the tapped notification in notification center. So you can just do:

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

    // This removes the notification from notification center
    [[UIApplication sharedApplication] cancelLocalNotification:notification];
}