startMonitoringSignificantLocationChanges Does not work in the background

0

I'm making an app that uses the device's location service. It necessarily needs to be capturing the positions when there is a change of location and must capture in all situations ( background / foreground / killed), so I am using the startMonitoringSignificantLocationChanges () method , but when I send it to background, the capture of positions only runs for some more time and stops, after that it does not capture anymore. We locomovo the distance that the documentation suggests for update (500m) of position and nothing happens. What can I be doing wrong? Note: In the simulator works perfectly, but in the physical device does not work.

The Info.plist file has the background setting enabled

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

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if (launchOptions != nil) {
        let locationManager = CLLocationManager()
        locationManager.delegate = ViewController()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.activityType = CLActivityType.other
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.startUpdatingLocation()
    }

    return true
}

func applicationDidEnterBackground(_ application: UIApplication) {
    let locationManager = CLLocationManager()
    locationManager.delegate = ViewController()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.activityType = CLActivityType.other
    locationManager.allowsBackgroundLocationUpdates = true
    locationManager.startMonitoringSignificantLocationChanges()
}

ViewController.swift

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {    
    //Trato a captura da nova localização 
}
    
asked by anonymous 12.04.2017 / 22:50

1 answer

-1

Two suggestions ...

I noticed that in the code you submitted, you are not requesting permission to get the user's location ... Maybe that's a problem. To resolve this, just put in the viewDidLoad: locationManager.requestWhenInUseAuthorization ()

Another possibility is that in the documentation it is stated that this function does not send notifications followed in less than 5 minutes. That is, even if you move more than 500 meters, if it is not 5 minutes after the last notification, the app will not notify you again until the 5 minutes have passed.

If you need to check the user location changes more often, I think you'll have to use startUpdatingLocation () and calculate whether or not the user moved enough or not ...

    
13.04.2017 / 21:19