Mic*_*ael 5 objective-c nsdate ios uilocalnotification
我想执行一个UILocalNotification在上午9:00每天,永远,只要应用程序是开放的.我发现最接近的是:
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [[NSDate date] dateByAddingTimeInterval:60*60*24];
notification.alertBody = @"It's been 24 hours.";
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
Run Code Online (Sandbox Code Playgroud)
但是,此代码仅UILocalNotification在24小时内执行一次,而不是在指定时间执行.我一直在寻找利用NSDate某种方式,但一直没有在哪里.
代码将AppDelegate在application didFinishLaunchingWithOptions方法中执行.如果有人打开应用程序并在上午8:59将其放在后台,UILocalNotification那么仍然会在上午9:00执行.
一个NSDateComponent不能用于此,因为我必须声明一年,一个月和一天,但我想UILocalNotification每天执行此操作而无需编辑代码.
小智 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];
Run Code Online (Sandbox Code Playgroud)