我正在调用startMonitoringSignificantLocationChanges(),我注意到这使得位置服务不断运行,这使得电池消耗更多。
以下是我的代码,这不是完整的代码。
class CurrentLocationController:UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
locationManager = delegate.locationManager
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.activityType = CLActivityType.AutomotiveNavigation
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
...
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .Authorized {
locationManager.startMonitoringSignificantLocationChanges()
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if let location = locations.first as? CLLocation {
var update = GMSCameraUpdate.setTarget(location.coordinate, zoom: zoomSlider.value)
mapView.moveCamera(update)
saveLocation(location)
}
}
func saveLocation2DB(location:CLLocation) {
locationManager.stopUpdatingLocation()
...
}
有没有什么方法可以让我的应用程序只在有任何重大的位置变化并且不消耗大量电池时从后台获取应用程序?
答案 0 :(得分:0)
要解决此问题,请调用CLLocationManager类的deferredLocationUpdatesAvailable类方法,以确定设备是否支持延迟位置更新。
调用CLLocationManager类的allowDeferredLocationUpdatesUntilTraveled:timeout:方法开始推迟位置更新。至 防止自己多次调用allowDeferredLocationUpdatesUntilTraveled:timeout:方法,委托使用内部属性来跟踪更新是否已被延迟。它在此方法中将属性设置为YES,并在延迟更新结束时将其设置为NO。
请参阅示例代码:
// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// Add the new locations to the hike
[self.hike addLocations:locations];
// Defer updates until the user hikes a certain distance
// or when a certain amount of time has passed.
if (!self.deferringUpdates) {
CLLocationDistance distance = self.hike.goal - self.hike.distance;
NSTimeInterval time = [self.nextAudible timeIntervalSinceNow];
[locationManager allowDeferredLocationUpdatesUntilTraveled:distance
timeout:time];
self.deferringUpdates = YES;
}
}
有关详细信息,请阅读this文档的第19页。
希望这会有所帮助!!