如何连续30天设置UILocalNotification

时间:2013-10-31 12:49:56

标签: ios iphone nsdate uilocalnotification

我想在每天上午8:00连续30天安排UILocalNotificaion,我想仅使用一个UILocationNotification实例来实现该功能。这是我安排本地通知的代码。

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];
NSDate *date = [[NSDate alloc] init];
date = [formatter dateFromString:@"08:00"];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = date;
localNotification.timeZone=[NSTimeZone defaultTimeZone];
localNotification.alertBody = @"You just received a local notification";
localNotification.alertAction = @"View Details";
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.repeatInterval = NSDayCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[formatter release];
[date release];

它将在上午08:00永远发出每日通知,但我希望仅连续30天收到通知。最简单的解决方案是启动30个UILocalNotifications,但我希望使用1个UILocalNotification实例执行此操作。我怎样才能做到这一点?请帮忙。

2 个答案:

答案 0 :(得分:4)

在UILocalNotification中,userInfo属性在创建通知时保存NSDate对象。 当您打开通知时, 用userinfo中的日期检查当前日期。如果差异超过30天,您可以取消本地通知。

答案 1 :(得分:0)

NSDate *now = [NSDate date];

// now a NSDate object for now + 30 days
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:30];
NSDate *endDate = [gregorian dateByAddingComponents:offsetComponents toDate:now options:0];

之后检查:

if([currentDate isEarlierDate:endDate]){
//Fire the notification
}