获得具有良好准确度的LocationUpdates而不会耗尽电池的最佳方法

时间:2017-01-27 01:07:38

标签: ios swift cllocationmanager energy

我一直在尝试实施一个不断更新服务器用户位置的LocationView控制器。当我调试应用程序时,我注意到,我提供的SourceCode使我的电话电池耗尽了比平时快很多。我是否必须应对此问题,或者有什么办法,而不是减少LocationRequirements,以改进以下代码中的PowerUsage?

class LocationViewController: UIViewController {
  // MARK: - Outlets
  @IBOutlet var mapView: MKMapView!

  fileprivate var locations = [MKPointAnnotation]()
  var updatesEnabled: Bool = false;

  var defaultCentre: NotificationCenter = NotificationCenter.default
  //- NSUserDefaults - LocationServicesControl_KEY to be set to TRUE when user has enabled location services.
  let UDefaults: UserDefaults = UserDefaults.standard;
  let LocationServicesControl_KEY: String = "LocationServices"


  public var lastPosition: Date?;

  public lazy var locationManager: CLLocationManager = {
    let manager = CLLocationManager()
    manager.distanceFilter = 20;
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.delegate = self
    manager.requestAlwaysAuthorization()
    return manager
  }()

  public var routeLine: MKPolyline = MKPolyline() //your line
  public var routeLineView: MKPolylineView = MKPolylineView(); //overlay view
  // MARK: - Actions
  @available(iOS 9.0, *)
  @IBAction func enabledChanged(_ sender: UISwitch) {
    if sender.isOn {
      self.UDefaults.set(true, forKey: self.LocationServicesControl_KEY)
      locationManager.startUpdatingLocation()
      locationManager.allowsBackgroundLocationUpdates = true
      self.updatesEnabled = true;
    } else {
      self.UDefaults.set(false, forKey: self.LocationServicesControl_KEY)
      locationManager.stopUpdatingLocation()
      self.updatesEnabled = false;
      self.timer.invalidate()
      locationManager.allowsBackgroundLocationUpdates = false
    }
  }

  @IBAction func accuracyChanged(_ sender: UISegmentedControl) {
    let accuracyValues = [
      kCLLocationAccuracyBestForNavigation,
      kCLLocationAccuracyBest,
      kCLLocationAccuracyNearestTenMeters,
      kCLLocationAccuracyHundredMeters,
      kCLLocationAccuracyKilometer,
      kCLLocationAccuracyThreeKilometers]
    locationManager.desiredAccuracy = accuracyValues[sender.selectedSegmentIndex];
  }

  // MARK: - Override UIViewController
  override func viewDidLoad() {
    mapView.delegate = self;
  }
}

// MARK: - MKMapViewDelegate
extension LocationViewController: MKMapViewDelegate {
  func addRoute() {
    mapView.remove(self.routeLine);
    var pointsToUse: [CLLocationCoordinate2D] = [];
    for i in locations {
      pointsToUse += [i.coordinate];
    }
    self.routeLine = MKPolyline(coordinates: &pointsToUse, count: pointsToUse.count)
    mapView.add(self.routeLine)
  }
}

// MARK: - CLLocationManagerDelegate
extension LocationViewController: CLLocationManagerDelegate {

  func isUpdateValid (newDate: Date) -> Bool{
    var interval = TimeInterval()
    if(lastPosition==nil){lastPosition=newDate}
    interval = newDate.timeIntervalSince(lastPosition!)
    if ((interval==0)||(interval>=self.UpdatesInterval)){
      return true
    } else {
      return false
    }
  }

  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let mostRecentLocation = locations.last else {
      return
    }
    if(isUpdateValid(newDate: mostRecentLocation.timestamp)){
      let position = MKPointAnnotation();
      position.coordinate=mostRecentLocation.coordinate;
      self.locations.append(position);
      self.addRoute();

      self.locationAPI.postLocation(location: mostRecentLocation)
      lastPosition=mostRecentLocation.timestamp
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您需要限制GPS"点亮"不知何故。如果您已经设置为不断提供高精度的GPS读数,它将保持GPS通电并且您将使用大量电力。对此没有什么可做的。

的可能性:

你可以每10分钟唤醒一次GPS,运行它直到你获得良好的阅读,然后将其关闭。

当您的应用首次启动时,您会获得良好的阅读,然后订阅重要的位置更改,当您获得更新时,启动位置更新,获取新修复,然后再次关闭位置更新。

我不确定您是如何做第一个选项的,因为Apple不会让您的应用在后台无限期运行。您需要让您的应用程序在整个时间内保持清醒并在前台运行,这也会比允许其进入睡眠状态更快地耗尽电池。