【发布时间】:2012-05-29 04:39:19
【问题描述】:
我目前正在编写一个应用程序,该应用程序依赖于位置跟踪并将有关位置的数据发送到服务器。然而,问题是它必须 24/7 运行,目前我遇到了每 2-3 天发生一次的随机崩溃。为了使应用程序在后台持续运行,我所做的是将 NSTimer 放在 applicationDidEnterBackground 方法旁边的 beginBackgroundTaskWithExpirationHandler 方法中。计时器每分钟执行一次并停止/启动定位服务。
代码基本上是这样的:
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 秒。
我真的没有想法,崩溃发生的原因可能是什么?
【问题讨论】:
-
developer.apple.com/library/IOs/#documentation/iPhone/… 这个链接是多任务处理和背景资料的文档。它可能包含我们都在寻找的信息。
-
是的,我曾经做过一个应用程序,你可能想为你的计时器使用 NSRunLoopCommonModes
-
您看过 WWCD 2010 会议“在 iOS 4 中使用核心位置”和相关的示例应用程序“面包屑”吗? developer.apple.com/videos/wwdc/2010 他们描述了如何在后台使用核心位置而不使用任何计时器技巧。
标签: ios cocoa-touch networking background