ios后台任务计时器

时间:2015-10-23 07:43:55

标签: ios objective-c background-task

我正在设计一个应用程序,需要在后台模式下的某个时间向服务器发送数据。所以我想知道: 应用程序是否可以在我安排它(仅一次)后24小时执行一段代码?

非常感谢!

1 个答案:

答案 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"];

}

希望对你有所帮助。