我需要在后台执行一些计算。这是正确的方法吗?
重要请参阅 onPerformBackgroundTask。方法的第一部分结束了后台任务。是否有可能在应用程序暂停之前调用方法的第二部分?
- (void)applicationDidEnterBackground:(UIApplication *)application {
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
if ([self isNeedTimeToFinishTask])
{
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
if (!backgroundTimer)
{
self.backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:540 target:self selector:@selector(onPerformBackgroundTask:) userInfo:nil repeats:YES];
}
}
-(void) onPerformBackgroundTask:(id) sender
{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
if ([self isNeedTimeToFinishTask])
{
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
}
}
-(void) endBackgroundTask
{
if ([backgroundTimer isValid])
{
[backgroundTimer invalidate];
[backgroundTimer release];
}
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}