I am trying to get the current location whenever required and stop updating locations immediately. For this I wrote following code but continuos waiting on volatile flag doen’t seem to working. It doesn’t fire location updates evens when I am waiting on the flag. Could someone please tell me what’s wrong in my code. Thanks.
CurrentLocation.h file:
@property (nonatomic, assign) volatile BOOL locationUpdatedFlag;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *currentLocation;
CurrentLocation.m file:
@synthesize currentLocation = _currentLocation;
@synthesize locationManager = _locationManager;
@synthesize locationUpdatedFlag = _locationUpdatedFlag;
- (void)xxx
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[self.locationManager startUpdatingLocation];
self.locationUpdatedFlag = NO;
while(!self.locationUpdatedFlag)
[NSThread sleepForTimeInterval:.1];
// Use self.currentLocation
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
self.currentLocation = newLocation;
self.locationUpdatedFlag = YES;
[manager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"Error from Location Manager");
self.locationUpdatedFlag = YES;
}
The common way to fix this would be to remove the
while(){sleep}part and move the// Use self.currentLocation operationsinto the separate method called fromlocationManager:didUpdateToLocation:fromLocation:after you stop the manager. That is the most natural use of the delegate and you’ll want to use it. Other than that there are plenty of other solutions like adding observer tolocationUpdatedFlagkeypath or creating aseparatethread manually to wait for it sleeping like you did.