ios - 应用耗电过多

标签 ios swift core-location cllocationmanager

在构建了我想要的 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.

最佳答案

你有两个选择:

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

尝试第一个,如果它在设备上不可用,你必须牺牲你的 10m 目标

关于ios - 应用耗电过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36316701/

相关文章:

ios - 更新 TestFlight 后显示问题

iphone - 如何在 UITextView iPhone 应用程序中控制复制、粘贴、全选、定义?

ios - 使用 Xcode 和 Swift 在 pageControler 中播放声音文件

ios - CLLocation高程精度

ios - 在 Swift 中将 CLLocation 转换为 MKMapItem

objective-c - 类方法在 iOS 中如何工作?

ios - Swift - 就地更新对象

arrays - 如何在 swift 函数中返回一个 inout(引用)?

ios - 键盘打开时移动菜单(快速)

objective-c - -[UIView setRegion :animated:]: unrecognized selector sent to instance