简体   繁体   中英

CLLocationManager didUpdateLocations is just called twice in background mode

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.

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM