continuous iOS location updates in background

Viewed 2450

I am trying to create a simple iOS app that will continuously track location in the background and notify with high accuracy when the user has entered a specific region (don't want to use region monitoring because it's not accurate or fast enough for what I want).

This app works fine in the foreground but once I go into the background it does not work.

I created a test app to investigate how background location updates work. I made a simple app that just prints out a message when a location update happens (to the log).

What I see is that in foreground mode the updates happen as expected but when I lock my phone and the app switches to background the location updates happen for about 30 seconds and then stop. There is no mention in the Apple docs (that I can find) explaining this behavior.

I made sure that I enabled background processing in the info.plist (done in "capabilities" --> "background modes" --> "location updates")

Here is the code I used to test this:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

let locationManager = CLLocationManager() 
var counter = 0
override func viewDidLoad() {
    super.viewDidLoad()

    // configure location updates
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = 0.1
    locationManager.pausesLocationUpdatesAutomatically = false

    locationManager.requestAlwaysAuthorization()

    locationManager.startUpdatingLocation()

}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("location updated! \(counter)")
    counter = counter + 1
}

Any ideas on what I might be missing? I tried different location accuracy settings (such as BestForNavigation, etc) and no change.

Thanks.

3 Answers

You have to add this in your plist :

<key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>

add this

locationManager.allowsBackgroundLocationUpdates = true

I think this might be the answer: allowsBackgroundLocationUpdates.

Apps that want to receive location updates when suspended must include the UIBackgroundModes key (with the location value) in their app’s Info.plist file and set the value of this property to true.

...

The default value of this property is false.

Are you setting that?

You can add these two line to make it working in background mode:

locationManager!.allowsBackgroundLocationUpdates = true
locationManager!.pausesLocationUpdatesAutomatically = false
Related