Eslam Hamdy
Eslam Hamdy

Reputation: 7396

CLLocationManager doesn't get location

I'm Using CLLocationManager to get the current location of the device and i tried to get the location property in order to get the longitude and latitude as follows:

-(void)getCurrentLocation{
CLLocationManager *manager=[[CLLocationManager alloc]init];;
manager.delegate=self;
manager.desiredAccuracy=kCLLocationAccuracyBest;
self.currentLocation=manager.location;
NSLog(@"Current Lat :%f",self.currentLocation.coordinate.latitude);
NSLog(@"Current Long :%f",self.currentLocation.coordinate.longitude);

[manager startUpdatingLocation];
}

Given that:

self.currentLocation is a property inside my class (Which is the CLLocationManagerDelegate) as follows:

.h

@property(nonatomic,strong) CLLocation *currentLocation;

and the getter in the .m is as follows:

-(CLLocation *)currentLocation{
if (!_currentLocation) {
    _currentLocation=[[CLLocation alloc]init ];
}
return _currentLocation;

}

I forget to say that i have implemented the didUpdateToLocation Method as follows:

-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
      fromLocation:(CLLocation *)oldLocation {
NSLog(@"didUpdateToLocation");
CLLocation *loc=newLocation;
if (loc!=nil) {
    self.currentLocation=loc;

}  

}

I also tried to put this statement after the startUpdateLocation call:

    self.currentLocation=manager.location;

the problem is that when i call the previous function getCurrentLocation the two NSLogs inside it prints 0.000000 which means that manager.location isn't working and the weird thing is that the first NSLog inside didUpdateToLocation doesn't printed , thanks in advance

Upvotes: 1

Views: 1365

Answers (1)

MartinHN
MartinHN

Reputation: 19812

You can't just read the location from the CLLocationManager. It needs to update its location before that property is assigned:

The value of this property is nil if no location data has ever been retrieved.

CLLocationManager SDK

You must implement the delegate method locationManager:didUpdateLocations:

And when that is called you can read the location property, or look at the locations argument:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    self.currentLocation = [locations firstObject];

    NSLog(@"Current Lat :%f",self.currentLocation.coordinate.latitude);
    NSLog(@"Current Long :%f",self.currentLocation.coordinate.longitude);

    [manager stopUpdatingLocation]
}

You can call [manager stopUpdatingLocation] when you get the first call, so it doesn't keep running.

Upvotes: 2

Related Questions