iOS每日本地推送通知

我想在每天早上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 ,但一直没有得到的地方。

代码将在application didFinishLaunchingWithOptions方法的AppDelegate中执行。 如果有人打开应用程序并在上午8:59将其置于后台,则UILocalNotification将在上午9:00仍然执行。

一个NSDateComponent将不会工作,因为我将不得不声明年,月和日,但我想每天执行此UILocalNotification而不必编辑代码。

您需要查找上午9点发生的下一个时间,并在当时设置本地通知:

 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. 下一个火灾date获取正确的NSDate。
  2. 设置本地通知,以便每24小时发射一次

这是一个片段:

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

在安排通知之前,只需设置repeatInterval

 localNotification.repeatInterval = NSCalendarUnitDay;