didupdatetolocation called multiple times – CLLocationManagerDelegate

Introduction to Issue

In CLLocationManager, developer generally use this class to configure, start, and stop the Core Location services. In application to get current location for required app purpose. When this class get user location if location permission are enabled then it call didupdatetolocation delegate methods as location is change by any difference this delegate method calls.

Solution 1: to didupdatetolocation called multiple times – CLLocationManagerDelegate

Step 1) Initialise a boolean globally and set default value false

var isLocationUpdated : Bool = false;

Step 2) Implement one time setting of boolean true so that when next time this method will be called it will ignore it

//cl location manager delegates
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if (!isLocationUpdated) {
isLocationUpdated = true
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
lblLocationName.text = "Current Location Lat = \(locValue.latitude), Long = \(locValue.longitude)"
// do whatever you want to do with location coordinate
}
}

Solution 2: to didupdatetolocation called multiple times – CLLocationManagerDelegate

Step 1) While intializing CLLocationManager, there is a property in CLLocationManager which is ‘distanceFilter’ by setting this some value as per your requirement can lead to make what you want in your app.

locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 200

Solution 3: to didupdatetolocation called multiple times – CLLocationManagerDelegate

Step 1) you can directly stop updating CLLocationManager and can set nil to delegate property which will make locationManager to loose all connection and you will get your desired thing but only use this if you are not going to need update location thing next time.

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
[manager stopUpdatingLocation];
manager.delegate = nil;
//...... do something
}

Leave a Comment