Reputation: 527
I'm trying to set up a system where users with a certain account type will always have their location tracked, even when it is terminated and isn't in use. I also want to constantly update that location (in longitude and latitude) into firebase whenever any change in location occurs. I've read about needing to use startMonitoringSignificantLocationChanges however I can't seem to figure out how to use this and it only seems to from what I've read to update it only if a location change of over 1km has occurred.
Ankit's answers works well, but I'm still confused about how would I go about updating the user's location when the app is terminated into my database through the app delegate.
Upvotes: 2
Views: 752
Reputation: 3647
Well first of all, you must enable background mode in the
Xcode Project > Capabilities pane.
If you want updates even when your app is terminated, you must use startMonitoringSignificantLocationChanges to get location updates.
Limits: Event will fire when device moves 500 meters or more from its previous notification.
Tradeoff:
Normally use: startUpdatingLocation()
for frequent events
but in applicationWillTerminate(_ application: UIApplication)
modify that locationObject and call its startMonitoringSignificantLocationChanges()
Use below method:
func startBackgroundLocationUpdates() {
// Create a location manager object
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
// Request location authorization
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
// Enable automatic pausing
locationManager.pausesLocationUpdatesAutomatically = true
// Specify the type of activity your app is currently performing
locationManager.activityType = .fitness
// Enable background location updates, after iOS 9 its must
locationManager.allowsBackgroundLocationUpdates = true
// Start location updates in terminated mode as well
locationManager.startMonitoringSignificantLocationChanges()
//or for frequents events
locationManager.startUpdatingLocation()
}
Now location updates are delivered to your delegate’s locationManager(_:didUpdateLocations:) method.
If your app is terminated, the system automatically relaunches the app into the background if a new event arrives. with options dictionary passed to application(_:didFinishLaunchingWithOptions:) methods of your app delegate contains the key location to indicate that your app was launched because of a location event.
Now since your app has been launched in background , you can implement your logic here to send updates to server but do remember following thing:
Upon relaunch, you must still configure a location manager object and call this method startMonitoringSignificantLocationChanges
to continue receiving location events.
Also remember to call the stopUpdatingLocation method of the location manager object when location updates are no longer needed
Upvotes: 1