【问题标题】:How is it possible to ensure a constant continuous update of location when iOS app is in the background?当 iOS 应用程序在后台时,如何确保不断更新位置?
【发布时间】:2013-05-27 01:44:03
【问题描述】:

我们的 iOS 应用程序的一个要求是在后台监控位置变化。我们已经实现了“locationManager startMonitoringForRegion:region”,不幸的是我们在彻底测试应用程序时意识到它太不精确,无法满足我们的需求。

然后我们使用“locationManager startUpdatingLocation”来提高位置的准确性。在前台一切都很好,这个位置精度几乎是我们想要的。

现在的问题是当应用程序在后台时,没有定期调用事件“didUpdateLocations”。我们通过查看日志文件观察到这一点。发生的事情几乎总是一样的,前 15 分钟应用程序会定期更新位置,然后突然停止。在大约 5 分钟的休息后,它会再次更新位置大约 15 分钟。这继续以同样的方式。

我们可能在后台处理的实现中犯了错误。

UIApplication *app = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier bgTask = 0;

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{

    if(rootViewController._selectedLocation == nil)
    {
        NSLog(@"selected location is nil and app entered background");
        [rootViewController.locationManager stopUpdatingLocation];
    }
    else
    {
        NSLog(@"selected location is not nil and app entered background");
        [rootViewController.locationManager startUpdatingLocation];
    }
    [app endBackgroundTask:bgTask];

}];

这似乎大约每 20 分钟调用一次,并且位置会再次更新。我们做错了什么,我们如何才能在没有任何中断的情况下定期更新位置?我们用 iPhone 5 进行了测试,知道它是静止的也很重要。

【问题讨论】:

  • 你在后台调用过 stopUpdatingLocation 吗?顺便说一句,如果您的 plist 中有 location 键,我相信您不需要使用 beginBackgroundTaskWithExpirationHandler:
  • 另外,您为CLLocationManager 上的activityType 属性设置了什么?您是否将pausesLocationUpdatesAutomatically 设置为否?
  • 非常感谢,您刚刚解决了它。我将 CllocationManager 的 pausesLocationUpdatesAutomatically 设置为 No。应用程序现在会在后台定期更新位置。是的,看起来 beginBackgroundTaskWithExpirationHandler: 是不必要的。再次感谢!
  • 我必须提到一个有趣的问题。我还在 iPhone 4S 上测试了没有上述解决方案的应用程序,由于某种原因,位置更新从未中断。
  • 4S有ios 6吗? pausesLocationUpdatesAutomatically 属性是 ios 6 的新特性。

标签: ios background core-location cllocationmanager


【解决方案1】:

您应该将以下值添加到您的应用程序 plist 文件中:

所需的背景模式

它是一个数组,告诉系统您的应用在后台时需要什么。对于第0项的位置,你应该告知值:

应用注册位置更新

如有疑问,您可以在此链接中看到我在说什么:iOS Multitasking: Background Location

【讨论】:

  • 感谢您的链接和建议。值“应用程序注册位置更新”已添加到“所需后台模式”下的 plist。这似乎不是问题,错误在其他地方。我会仔细看看你发给我的链接。
猜你喜欢
  • 2018-07-13
  • 1970-01-01
  • 2015-03-11
  • 2012-07-05
  • 1970-01-01
  • 2016-02-18
  • 2019-04-18
  • 1970-01-01
  • 2015-09-05
相关资源
最近更新 更多