我想使用位置更新和"allowDeferredLocationUpdatesUntilTraveled"在后台执行任务
但它现在确实推迟了定位,每1秒发生一次(这是基于准确性),并且它是由位置管理器中的条件触发的:didFinishDeferredUpdatesWithError:
我根据文档进行了测试
我设置了位置更新后台模式
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
if CLLocationManager.authorizationStatus() == .NotDetermined{
locationManager.requestAlwaysAuthorization()
}
locationManager.delegate = self
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.activityType = CLActivityType.Fitness
locationManager.allowsBackgroundLocationUpdates = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
if UIApplication.sharedApplication().applicationState == .Background && !self.bDeferringUpdates // && CLLocationManager.deferredLocationUpdatesAvailable()
{
self.bDeferringUpdates = true;
self.locationManager.allowDeferredLocationUpdatesUntilTraveled(CLLocationDistanceMax, timeout: 60*60)
}
}
func locationManager(manager: CLLocationManager, didFinishDeferredUpdatesWithError error: NSError?) {
self.bDeferringUpdates = false
}
有人说它在调试模式或充电模式下不起作用,所以我在不充电的情况下测试了它。
我记录了事件,但它每秒钟都会发生,而且没有延迟。
日志位于之下
2016-06-09 02:51:39 - didUpdateLocations
2016-06-09 02:51:40 - didUpdateLocations
2016-06-09 02:51:41 - didUpdateLocations
2016-06-09 02:51:42 - didUpdateLocations
2016-06-09 02:51:43 - didUpdateLocations
2016-06-09 02:51:44 - didUpdateLocations
2016-06-09 02:51:45 - didUpdateLocations
2016-06-09 02:51:46 - didUpdateLocations
2016-06-09 02:51:47 - didUpdateLocations
2016-06-09 02:51:48 - didUpdateLocations
2016-06-09 02:51:49 - didUpdateLocations
2016-06-09 02:51:49 - didFinishDeferredUpdatesWithError
2016-06-09 02:51:50 - didUpdateLocations
2016-06-09 02:51:50 - allowDeferredLocationUpdatesUntilTraveled
2016-06-09 02:51:51 - didUpdateLocations
2016-06-09 02:51:52 - didUpdateLocations
2016-06-09 02:51:53 - didUpdateLocations
2016-06-09 02:51:54 - didUpdateLocations
我从凌晨1点52分到8点03分进行了测试,没有充电
凌晨1点52分,带100%电池,上午8:03,电池为87%
在6小时内消耗13%的电池电量
我想念它吗?
从您的日志中,我无法判断它是否在推迟。你至少需要看看error.code
在locationManager:didFinishDeferredUpdatesWithError:
中是什么,还需要看看你在locationManager:didUpdateLocations
中的locations
阵列中得到了多少个位置点
错误
kCLErrorDeferredFailed
,则表示GPS不可用,或者位置管理器此时无法获得位置修复kCLErrorDeferredNotUpdatingLocation
(如果未能启动位置管理器更新)kCLErrorDeferredDistanceFiltered
,如果您设置了距离过滤器(您没有设置)kCLErrorDeferredAccuracyTooLow
,如果你的精度低于10米(看起来你的精度足够好)kCLErrorDeferredCanceled
如果发生其他错误(你的应用程序在前台,你的手机正在充电,你有另一个应用程序在使用连续定位)
我鼓励您查看(CLLocationManager的参考资料)
此外,请记住,只有当操作系统有机会节省电池时,才会延迟定位。这始于手机进入低功耗待机模式。即使有后台网络请求,也可能不会得到位置延迟,因为CPU在后台处于活动状态。(一些人在不同的论坛上表示,背景音频播放也会使手机无法进入完全待机状态,因此可能不会推迟定位)。