我有一段代码可以让我在特定时间更新我的应用程序:
MainViewController.m:
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
[components setHour:14];
[components setMinute:5];
[components setSecond:0];
NSDate *nextAlarm = [calendar dateFromComponents:components];
if ([nextAlarm timeIntervalSinceNow] < 0)
{
nextAlarm = [nextAlarm dateByAddingTimeInterval:60*60*24];
}
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
[localNotification setRepeatInterval: NSCalendarUnitDay];
[localNotification setFireDate:nextAlarm];
[localNotification setAlertBody:@"It's been one day"];
[localNotification setValue:nextAlarm forKey:@"fireDate"];
UIApplication *app = [UIApplication sharedApplication];
[app scheduleLocalNotification:localNotification];
AppDelegate.m
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *synchroDate = notification.fireDate;
NSDate *currentDate= [NSDate date];
NSLog(@"difference : %f", [synchroDate timeIntervalSinceDate:currentDate]);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger comps = (NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute);
NSDateComponents *date1Components = [calendar components:comps
fromDate: currentDate];
NSDateComponents *date2Components = [calendar components:comps
fromDate: synchroDate];
currentDate = [calendar dateFromComponents:date1Components];
synchroDate = [calendar dateFromComponents:date2Components];
BOOL result = [currentDate isEqual:synchroDate];
if (result)
{
[self autoSynchro];
}
我的问题是我希望在我的设备关闭时启动该代码。我可以看到通知在ipad主屏幕上很好地启动了,但功能没有启动...
可能我必须使用它:
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateInactive)
{
//Do checking here.
}
但如果它处于待机模式,如何启动它? 有什么想法吗?