问题
I'm using Parse and with geoPointForCurrentLocationInBackground I can stop updating once a location is received without having to manually stop it.
How do I stop updating location immediately right after I receive location using CLLocationManager?
Edit
I know [self.locationManager stopUpdatingLocation]; stops it. What I'm really asking is, how do I know I've received location for the first time then stop it immediately?
回答1:
After getting your location, use this method:
[self.locationManager stopUpdatingLocation];
self.locationManager = nil;
回答2:
Call stopUpdatingLocation
as soon as your didUpdateLocations
method is called.
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
[manager stopUpdatingLocation];
//store your location
self.location = [locations lastObject];
}
回答3:
BOOL first_time = YES; // public
Every time you start updating location set first_time to YES:
first_time = YES;
[self.locationManager startUpdatingLocation];
in your didUpdateUserLocation method:
if (userLocation == nil) {
NSLog(@"User location is nil. maybe wating for permission");
} else if (!CLLocationCoordinate2DIsValid(userLocation.coordinate)) {
NSLog(@"User location is not valid 2d coordinates. maybe called in background");
} else {
NSLog(@"Did update user location: %f %f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
// here is the first time you receive user location
if (first_time)
{
first_time = NO;
[self.locationManager stopUpdatingLocation];
}
}
回答4:
The opposite of stopMonitoringSignificantLocationChanges
is not stopUpdatingLocation
, it is startMonitoringSignificantLocationChanges
.
Check out the CLLocation documentation for further detail.
回答5:
call below method to save and stop location after you get it once
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
self.location = [locations lastObject]
self.locationManager.delegate = nil;
[self.locationManager stopUpdatingLocation];
}
回答6:
Finally found the answer in another question...reprinting it here because it took me a while to stumble on it.
I had to call this:
[_locationManager stopMonitoringSignificantLocationChanges];
Even though I never called startMonitoringSignificantLocationChanges in the first place, seems I had to "un-call" it...strange that it works this way, but as soon as I added that line, location services shut down promptly. Hope this helps someone else.
回答7:
Once current location update stop location manager using stopUpdatingLocation
.
region.center = self.mapView.userLocation.coordinate;
if (region.center.longitude != 0 && region.center.latitude != 0) {
[self.locationManager stopUpdatingLocation];
}
回答8:
self.yourLocationManager.stopUpdatingLocation()
来源:https://stackoverflow.com/questions/31916504/how-to-stop-updating-location-once-i-get-current-location