基于位置追踪的iOS全时后台服务

4
我正在编写一个依赖于位置跟踪并向服务器发送有关位置的数据的应用程序。然而,问题在于它必须24/7运行,目前我正在经历每2-3天发生一次的随机崩溃。为了使应用程序在后台持续运行,我在applicationDidEnterBackground方法中使用beginBackgroundTaskWithExpirationHandler方法放置了一个NSTimer。计时器每分钟执行一次,并停止/启动位置服务。
这是一个示例崩溃日志Here is a sample crash log 代码基本上看起来像这样:
UIApplication *app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTaskId = 0;

bgTaskId = [app beginBackgroundTaskWithExpirationHandler:^{
    NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 1 * 60.0 target: self selector: @selector(onTick) userInfo: nil repeats: YES];
    [t fire];

    if (bgTaskId != UIBackgroundTaskInvalid){
        [app endBackgroundTask: bgTaskId];

        bgTaskId = UIBackgroundTaskInvalid;
    }
}];

我正在使用 GCDAsyncSockets 进行连接,每个调用都有大约 30 秒的超时时间。
我真的没有想法,是什么原因导致崩溃发生?

1
这个链接是关于多任务和后台处理的文档。它可能包含我们所寻找的信息。 - Kaili
1
是的,我曾经在一个应用程序中做过这个,你可能想在你的计时器中使用NSRunLoopCommonModes。 - Greg Price
1
你看过 WWCD 2010 的“在 iOS 4 中使用核心定位”会议和相关的示例应用程序“Breadcrumbs”吗?http://developer.apple.com/videos/wwdc/2010/。它们描述了如何在后台使用 Core Location 而不使用任何计时器技巧。 - Jenn
1个回答

4
你的计时器可能会在任务失效后触发(即在[UIApplication sharedApplication].backgroundTimeRemaining到达0之后)。但是问题在于,你无法让应用程序在后台持续运行。如果你想定期执行代码,则唯一的选择是使用后台位置API,在plist中设置你的应用程序正在使用位置后台模式。你将会得到CLLocationManagerDelegate回调,并且当这些方法被调用时,你有一些时间来完成一些工作。
请参阅苹果文档,了解有关后台模式的详细信息:http://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html 以及位置感知手册:http://developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/Conceptual/LocationAwarenessPG/Introduction/Introduction.html#//apple_ref/doc/uid/TP40009497

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接