iOS后台任务(NSThread)死亡

时间:2011-07-17 18:29:41

标签: background asihttprequest nsthread cllocation

前几天我发布了一个关于NSThread的问题。最后,我设法让它每分钟都在后台运行。

该应用程序的目的是获取位置,然后调用Web服务,每隔X分钟在具有ASIHTTPRequest的服务器上更新它。

代码:

- (void)threadEntryPoint:(ActualizarPosicionGPS2AppDelegate *)paramSender{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    while([[NSThread currentThread] isCancelled] == NO){
        [NSThread sleepForTimeInterval:60.0f];
        if ([[NSThread currentThread] isCancelled] == NO &&
            [[UIApplication sharedApplication] backgroundTimeRemaining] != DBL_MAX) {
            [self hacerCosasBackground];
        }
    }

    [pool release];
}

hacerCosasBackground调用locationManager更新它的位置,然后将位置上传到服务器。

在应用程序中:didFinishLaunchingWithOptions:

[NSThread detachNewThreadSelector:@selector(threadEntryPoint:) toTarget:self withObject:self];


-(void) endTaskWidthIdentifier:(NSNumber *)paramIdentifier{
    UIBackgroundTaskIdentifier identifier = [paramIdentifier integerValue];
    [[UIApplication sharedApplication] endBackgroundTask:identifier];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
        NSNumber *backgroundTask = [NSNumber numberWithInteger:self.backgroundTaskIdentifier];
        [self performSelectorOnMainThread:@selector(endTaskWidthIdentifier:) withObject:backgroundTask waitUntilDone:YES];
        self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
    }];
}

然而,NSThread在关闭应用程序约10分钟后就会死亡。我在info.plist中注册了'UIBackgroundModes'位置。 我还读到了关于startMonitoringSignificantLocationChanges但我想让我的应用程序非常可配置(用户将能够设置他们想要更新位置的频率等等)并且我知道该方法每500米更新一次(这不好,我想要更频繁地更新位置。)

我该怎么办?有什么帮助吗?

非常感谢!

0 个答案:

没有答案