问题描述
您好,有人可以解释如何检查过期的UILocalNotifications并取消通知吗?
Hi can anyone please Explain How to check for Expired UILocalNotifications and cancel the notifications?
推荐答案
您无法取消已过期的通知,因为它已经过期/已触发".
安排通知时,如果 fireDate 为 nil 或过去日期,则该通知将立即被触发.因此,仅将通知安排在将来的日期.
When you schedule the notification, if the fireDate is nil or a past date then the notification will be fired immediately. So, schedule the notification for the future dates alone.
在 applicationDidEnterBackground 委托被调用时,所有通知(您称为过期的通知" )都将被触发.
By the time applicationDidEnterBackground delegate is called all the notifications(which you refer as "Expired Notifications") would have got fired.
触发通知后,如果它不是定期通知,则会自动删除.
Once a notification is fired it will be automatically removed if it is not an recurring notification.
要取消某个日期的本地通知
如果已到最后日期,请使用以下代码取消通知.从 didReceiveLocalNotificaiton:
方法或 didFinishLaunchingWithOptions:
方法调用此方法.
Use the following code to cancel a notification if the last date has reached. Call this method either from didReceiveLocalNotificaiton:
method or didFinishLaunchingWithOptions:
method.
- (void)stop:(UILocalNotification *)localNotif ifLastDate:(NSDate *)lastDate {
NSTimeInterval ti = 24*60*60; // One day
NSDate *expiryDate = [lastDate dateByAddingTimeInterval:ti];
NSDate *nextFireDate = [localNotif.fireDate dateByAddingTimeInterval:ti];
if ([nextFireDate compare:expiryDate] == NSOrderedDescending) {
[[UIApplication sharedApplication] cancelLocalNotification:localNotif];
}
}
didFinishLaunchingWithOptions:方法,
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Other Codes Here
Class cls = NSClassFromString(@"UILocalNotification");
if (cls != nil) {
UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (notification) [self stop:notification ifLastDate:aDate]; // aDate is the last date you want to check
}
// Other Codes Here
return YES;
}
didReceiveLocalNotification:方法,
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[self stop:notification ifLastDate:aDate]; // aDate is the last date you want to check
}
请注意,只有在应用程序运行时,才能取消本地通知.如果应用未运行,则无法取消通知.仅当在 lastDate
上触发通知后,只有通过点击操作按钮打开应用程序时,以上代码才会取消通知.如果不是,则在 lastDate 之后触发的通知上点击操作按钮会在打开应用程序时取消通知.
Note that you can cancel a local notification only when the app is running. You can not cancel a notification if the app is not running. The above code will cancel the notification only if the the app is opened by tapping the action button after the notification is fired on lastDate
. If not, the notification will be cancelled when the app is opened by tapping action button on a notification that fires after the lastDate.
这篇关于如何检查过期的UILocalNotifications?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!