Get location updates in background - only for Country change iOS

345 Views Asked by At

What is the best way in core location to get background location updates only when there is change in country?

2

There are 2 best solutions below

0
On

What you are looking for is called geofencing, there are great articles about it. Any way you'll need to implement functions like

func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) (CLLocationManagerDelegate)

func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) (CLLocationManagerDelegate)

open func requestAlwaysAuthorization() (CLLocationManager)

func startMonitoring(for region: CLRegion) (CLLocationManager)

0
On

You can use the reverseGeocodeLocation of the CLGeocoder to get the current country for your location.

func locationManager(_ manager: CLLocationManager, didUpdateLocations objects: [CLLocation]) {
    let location = objects.last!
    let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(location!) { (places, error) in
            if(error == nil){
                if(places != nil){
                    let place: CLPlacemark = places![0]
                    let country = place.country
                    // do something if its changed

                }
            } else {
                //handle error
            }

But the issue will be you need to be monitoring location for this to happen. You can use startMonitoringSignificantLocationChanges as one option or you could set desired accuracy to something big like kCLLocationAccuracyThreeKilometers both of which will reduce the amount of power used by location updates.