Search code examples
ioscllocationmanagerios11xcode9cllocation

Can't get background location update on iOS 11


I've added in .plist all 3 possible keys:

Privacy - Location Always and When In Use Usage Description

Privacy - Location When In Use Usage Description

Privacy - Location Usage Description

My code is:

private lazy var locationManager: CLLocationManager = {
    let manager = CLLocationManager()
    manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    manager.delegate = self
    manager.requestAlwaysAuthorization()
    return manager
  }()

 @IBAction func enabledLocationUpdate(_ sender: UISwitch) {
    if sender.isOn {
      locationManager.startUpdatingLocation()
    } else {
      locationManager.stopUpdatingLocation()
    }
  }

extension LocationViewController: CLLocationManagerDelegate {

  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let mostRecentLocation = locations.last else {
      return
    }


    NSLog("New location is \(mostRecentLocation)")
}

When app in foreground I can see location updates, but when I pressed home button - location updates stopped. What I'm doing wrong?

Xcode Version 9.0 (9A235) iOS 11.0.2


Solution

  • You could be missing two things:

    1. Set allowsBackgroundLocationUpdates to YES on the CLLocationManager object. See Apple Documentation
    2. Enable "location" as a background mode in your Info.plist file. See Apple Documentation