应用耗电过多

App consuming too much battery

构建了我想要的 iOS 应用程序后,我意识到由于位置服务,它消耗了太多电池。

背景:每当用户移动 10 米(30 英尺)时,我的应用程序都会通过网络调用服务器。这会触发 didUpdateLocation 函数。当该功能被触发时,我使用 NSURLSession 将用户坐标发送到服务器,仅此而已。

现在的问题在于,我无法在第一次更新后通过调用 locationManager.stopUpdatingLocation() 来关闭定位服务硬件,因为当用户决定再次移动时,我不会获得任何后续更新。此外,当应用程序在后台监控移动时,位置服务会保持活动状态,这也会拖累电池寿命。当涉及到这里的文档和其他问题时,我已经阅读了几乎所有关于这个问题的内容。

许多其他问题建议使用 NSTimer 并在经过一段时间后调用 startUpdatingLocation() 并且我收到了第一个位置更新并调用了 stopUpdatingLocation我的 didUpdateLocation 功能。所以我尝试了以下方法:

let timerAction = NSTimer(timeInterval: 6.0, target: self, selector: #selector(MapViewController().startLocationServices), userInfo: nil, repeats: true)
    timerAction.fire() 

func startLocationServices() {
    self.locationManager.startUpdatingLocation()
}

由于某种原因这没有奏效。但我的问题真正集中在当我必须使用 distanceFilter = 10.0 监视用户在前台和后台的移动时如何节省电池并使我的应用程序真正节能?

任何关于您所做的事情或您会推荐的事情的建议都将得到极大的寻求和赞赏。

谢谢!

编辑

@wain 建议使用 allowDeferredLocationUpdatesUntilTraveled:timeout:

Start the delivery of location updates before calling this method. The most common place to call this method is in your delegate’s locationManager:didUpdateLocations: method. After processing any new locations, call this method if you want to defer future updates until the distance or time criteria are met. If new events arrive and your app is in the background, the events are cached and their delivery is deferred appropriately.

您有 2 个选择:

  1. 使用allowDeferredLocationUpdatesUntilTraveled:timeout:
  2. 使用显着的位置变化

尝试第一个,如果设备上不可用,您必须牺牲 10 米的目标

我最终通过使用地理围栏解决了这个问题。我创建一个 CLCircularRegion 并调用 startMonitoringForRegion(_:)。每次用户离开该区域(10 米)时,我都会向服务器发出请求以查看他现在所在的位置并更新该区域。这几乎不使用电池,而这正是我正在寻找的。查看 CLLocationManagerCLLocationManagerDelegateCLCircularRegion 类 了解如何执行此操作。我希望这对某人有用。