UIApplication scheduledLocalNotifications is empty for past non-repeating notifications

久未见 提交于 2020-01-13 04:55:26

问题


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];
}


来源:https://stackoverflow.com/questions/14215214/uiapplication-scheduledlocalnotifications-is-empty-for-past-non-repeating-notifi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!