24/7 twenty-four seven

iOS/OS X application programing topics.

iOS 4 のバックグラウンドタスク (Task completion) の制限時間は 10 分

下記のコードで確認。適当コードなのでマネしてはいけません。

- (void)onTimer:(id)timer {
    NSLog(@"Time remaining: %g", [[UIApplication sharedApplication] backgroundTimeRemaining]);
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"%s", __func__);
    
    UIDevice *device = [UIDevice currentDevice];
    
    BOOL backgroundSupported = NO;
    if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {
        backgroundSupported = device.multitaskingSupported;
    }
    
    if (backgroundSupported) {
        backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
            NSLog(@"%@", @"End background task.");
            [timer invalidate];
            timer = nil;
            [application endBackgroundTask:backgroundTask];
            backgroundTask = UIBackgroundTaskInvalid;
        }];
        
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
    }
}


実行結果。なんでか 5 秒前に終了しちゃうけど。

2010-06-30 21:14:43.761 Test[61557:207] -[AppDelegate applicationDidEnterBackground:]
2010-06-30 21:14:44.763 Test[61557:207] Time remaining: 598.998
2010-06-30 21:14:45.923 Test[61557:207] Time remaining: 597.838
2010-06-30 21:14:46.763 Test[61557:207] Time remaining: 596.998
2010-06-30 21:14:47.784 Test[61557:207] Time remaining: 595.977
2010-06-30 21:14:48.768 Test[61557:207] Time remaining: 594.993
(中略)
2010-06-30 21:24:32.743 Test[61557:207] Time remaining: 10.9981
2010-06-30 21:24:33.743 Test[61557:207] Time remaining: 9.99815
2010-06-30 21:24:34.743 Test[61557:207] Time remaining: 8.99815
2010-06-30 21:24:35.743 Test[61557:207] Time remaining: 7.99819
2010-06-30 21:24:36.743 Test[61557:207] Time remaining: 6.99812
2010-06-30 21:24:37.743 Test[61557:207] Time remaining: 5.99799
2010-06-30 21:24:38.743 Test[61557:207] Time remaining: 4.99807
2010-06-30 21:24:38.744 Test[61557:207] End background task.