只要应用程序处于打开状态,我希望每天都在上午9:00 执行UILocalNotification
。我发现的最接近的是:
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [[NSDate date] dateByAddingTimeInterval:60*60*24];
notification.alertBody = @"It's been 24 hours.";
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
但是,此代码仅在24小时内执行一次UILocalNotification
,而不是在指定时间执行。我一直在考虑以某种方式使用NSDate
,但一直没有。
代码将在AppDelegate
方法的application didFinishLaunchingWithOptions
中执行。如果有人打开应用程序并将其置于上午8:59 的后台,则UILocalNotification
仍将在上午9:00 执行。
NSDateComponent
无法使用此功能,因为我必须声明一年,一月和一天,但我想每天执行此UILocalNotification
而无需编辑代码
答案 0 :(得分:11)
您需要找到9am发生的NEXT时间,然后将当地通知设置为当时:
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:9];
// Gives us today's date but at 9am
NSDate *next9am = [calendar dateFromComponents:components];
if ([next9am timeIntervalSinceNow] < 0) {
// If today's 9am already occurred, add 24hours to get to tomorrow's
next9am = [next9am dateByAddingTimeInterval:60*60*24];
}
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = next9am;
notification.alertBody = @"It's been 24 hours.";
// Set a repeat interval to daily
notification.repeatInterval = NSDayCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
答案 1 :(得分:4)
您的问题有两个问题:
这是一个片段:
// 1st: find next fire date, using NSDateComponents
NSDate * date = [NSDate date];
NSDateComponents * components = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:date];
// Components will now contain information about current hour and minute, day, month and year.
// Do your calculation in order to setup the right date. Note that components reflect user timezone.
// For example, skip to the next day if current time is after 9:00:
if (components.hour >= 9) {
components.day += 1;
}
// Now fix the components for firing time, for example 9:00.
components.hour = 9;
components.minute = 0;
NSDate * fireDate = [[NSCalendar currentCalendar] dateFromComponents:components];
NSLog(@"Notification will fire at: %@", fireDate);
// 2nd: Schedule local notification with repetitions:
UILocalNotification * notification = [[UILocalNotification alloc] init];
notification.fireDate = fireDate;
notification.repeatInterval = NSDayCalendarUnit; // Here is the trick
notification.alertBody = @"It's been 24 hours.";
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
答案 2 :(得分:3)
在安排通知之前设置repeatInterval
localNotification.repeatInterval = NSCalendarUnitDay;