CLLocationManager didUpdateLocations is just called twice in background mode

2.3k Views Asked by At

I want to use CLLocationManager for updating the users current GPS Location in foreground and background. I registered the app for using the location background mode in info.plist and under the targets capabilities. On the iPhone simulator everything works fine but on my real iPhone the function didUpdateLocations just gets called twice when app is in background. I use a gpx file which simulates GPS data in Xcode. It works when the app is in foreground, I can see the progress on a MapView.

This is the code from my ViewController:

lazy var locationManager: CLLocationManager! = {
    let manager = CLLocationManager()
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.delegate = self
    manager.requestAlwaysAuthorization()
    manager.pausesLocationUpdatesAutomatically = false
    //manager.distanceFilter = 250
    return manager
}()



//Location manager delegate function

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    if(UIApplication.sharedApplication().applicationState == .Background){
        print("background call")
    }else{
        print("foreground call")
    }

    // Save GPS coordinates
    saveGpsCoordinates(locations[0])
}

I’m using: IOS 9 on an iPhone 5 and Xcode 7.0 beta 5

Does someone have an idea why I don’t get any background delegate calls on my real device?

Thanks.

4

There are 4 best solutions below

1
rmp On

Two things:

  1. I don't seen anywhere in your code a call to startUpdatingLocation.

  2. (Assuming 1 is correct) You said you are using a GPX file to simulate locations, if you are using a GPX file to simulate locations than that is not using the locationManager to get locations and since you did not call startUpdatingLocation, the locationManager is not actually running in the foreground or background.

0
Sjoerd Perfors On

Make sure you set pausesLocationUpdatesAutomatically to TRUE. Because you get more location updates when this is set to FALSE, even locations which look the same.

TRUE is also the default value.

1
StCleezy On

I had a similar issue after moving to iOS9.

As noted in the answer to the question below, make sure you are setting allowsBackgroundLocationUpdates to YES

allowsBackgroundLocationUpdates in CLLocationManager in iOS9

0
tùng nguyễn On

you should add NSLocationAlwaysUsageDescription in info.plist. Good luck!