我正在设计一个应用程序,需要在后台模式下的某个时间向服务器发送数据。所以我想知道: 应用程序是否可以在我安排它(仅一次)后24小时执行一段代码?
非常感谢!
答案 0 :(得分:0)
将日期存储在NSUserDefaults
中,然后再检查24小时..
NSDate *date = [[NSUserDefaults standardUserDefaults] objectForKey:@"CONSCIENCE_START_DATE"];
if (!date) {
// This is the 1st run of the app
date = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:date forKey:@"CONSCIENCE_START_DATE"];
}
NSString *str = [NSString stringWithFormat:@"%@",date];
NSLog(@" date string = %@",str);
NSTimeInterval secondsBetween = [[NSDate date] timeIntervalSinceDate:date]; // in seconds
int numberOfHours = secondsBetween / 3600; // convert in hours
NSLog(@"There are %d hours in between the two dates.", numberOfHours);
if (numberOfHours > 24) {
// do your code here ...
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"CONSCIENCE_START_DATE"];
}
希望对你有所帮助。