重复和取消UILocalNotification

时间:2014-09-14 10:33:47

标签: ios objective-c cocoa-touch uilocalnotification

我希望每分钟在我的应用程序中UILocalNotification触发一次可变次数,之后我想取消它。

我试图找到一个能让我这样做的参数。

1 个答案:

答案 0 :(得分:1)

1)安排通知

请注意.repeatInterval属性值。

UILocalNotification *reminder = UILocalNotification.new;
reminder.fireDate = fireDate;
reminder.timeZone = [NSTimeZone systemTimeZone];
reminder.alertBody = @"Your alert message";
reminder.alertAction = @"Your alert action";
reminder.soundName = UILocalNotificationDefaultSoundName;
reminder.repeatInterval = NSMinuteCalendarUnit;

[[UIApplication sharedApplication] scheduleLocalNotification:reminder];

2)处理通知(AppDelegate)

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    // custom handling code
}

注意:在iOS 8中,您必须为要调用的委托方法注册本地通知。

3)取消UILocalNnotification

[[UIApplication sharedApplication] cancelLocalNotification:reminder];

4)通知区分

要跟踪收到通知的次数,您必须唯一标识您的通知。您可以通过使用UILocalNotification实例.userInfo属性来实现此目的。

实施例

UILocalNotification *reminder = UILocalNotification.new;
...
reminder.userInfo = [NSDictionary dictionaryWithObject:@"custom value" forKey:@"notificationUniqueId"];
...

然后,当您在 2)中编写的委托方法中收到通知时,您可以检查您在userInfo字典中声明的通知唯一ID。知道这一点,您就可以跟踪UILocalNotification被解雇的次数,并在适当的时候取消它。

希望有所帮助!