iOS后台任务,争取一段时间处理后事

- (void)timerAction:(NSTimer *)timer {
    count++;
    UILabel *lable = (UILabel *)[self.window viewWithTag:100];
    NSString *str = [NSString stringWithFormat:@"%d", count];
    lable.text = str;
    if (count % 200 == 0) {
        UIApplication *application = [UIApplication sharedApplication];
        [application endBackgroundTask:taskId];
        taskId = [application beginBackgroundTaskWithExpirationHandler:NULL];
        count = 0;
    }
    NSLog(@"%@", str);

}


- (void)applicationDidEnterBackground:(UIApplication *)application
{
    taskId = [application beginBackgroundTaskWithExpirationHandler:^{
        [application endBackgroundTask:taskId];
    }];
    
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];


}
// 实际结果,偶然性被kill掉,175秒,300秒,在真机测试中。

你可能感兴趣的:(iOS后台任务,争取一段时间处理后事)