调用 startMonitoringSignificantLocationChanges() 会始终在状态栏上显示位置服务图标

Invoking startMonitoringSignificantLocationChanges() shows the location services icon always on the status bar

我正在调用 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()
    ...
}

有没有什么方法可以让我仅在位置发生重大变化且不消耗大量电池时才需要从后台获取我的应用程序?

要解决此问题,请调用 CLLocationManager class 的 deferredLocationUpdatesAvailable class 方法来确定设备是否支持延迟位置更新。

调用 allowDeferredLocationUpdatesUntilTraveled:timeout: CLLocationManager class 的方法开始延迟位置更新。到 防止自己多次调用 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 页。

希望这会有所帮助!!