Updating location to server every X minutes iOS

657 Views Asked by At

I am trying to update location from app to firebase after every X minutes ( any value less than 15mins is good).

I have enabled background mode for location and in following method I try to upload to Firestore document.

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

problem is in log I can see this method was called but in background no data is uploaded to firestore. In fact I works just after the app has entered in background sometimes but not at all after that.

Is there any workaround for this ?

3

There are 3 best solutions below

0
On

Check if you have set to true for allowsBackgroundLocationUpdates in your location Manager

locationManager?.allowsBackgroundLocationUpdates = true

Only if there is any update in location you will get the location updated in background. Also check if you have mentioned any distanceFilter in your location manager. If so, based on that only you will get the location update every X meters

locationManager?.distanceFilter = CLLocationDistance(X)

0
On

Use this code with Timer inside it to call update in Firestore:

write this code when starting your map call:

locationManager.startUpdatingLocation()
    locationManager.delegate = self

Avoid calling untill you don't want to stop location updating:

locationManager.stopUpdatingLocation()

Conform Delegate method:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = manager.location else {
        return
    }
    
    self.clLocation = location
    //Firestore condition here

}
0
On

Use this code

locationManager.startUpdatingLocation()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.delegate = self

Don't stop location updates in following delegate method.

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