how can i save latitude and longitude coordinates to a nsstring so that i can use it in another function. basically, i just want to show the values retrieved from the coordinates to be passed to a uilabel.
- (void)viewDidLoad
{
[super viewDidLoad];
[self getCurrentLocation];
NSLog(@"lat is %@ : lon is %@",self.latPoint, self.longPoint);
}
i tried to retrieve the above with a NSlog and it shows as null. i have two NSString properties created in my .h file as latPoint/longPoint
- (void)getCurrentLocation {
if ([CLLocationManager locationServicesEnabled]) {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
} else {
NSLog(@"Location services are not enabled");
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
self.latPoint = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
self.lonPoint = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
}
The behavior you are seeing is most likely because CLLocationManager
callbacks are asynchronous. Your NSLog call to print self.latPoint
and self.longPoint
(most likely) occur before the location manager has had time to find, and store, the current location.
If you move the NSLog(@"lat is %@ : lon is %@",self.latPoint, self.longPoint);
statement to the didUpdateLocations
method, then you should see it be called as soon as the location manager has found (and updated) your current location.
You simply need to be reactive to the CLLocationManager
callbacks rather than trying to make assumptions as to when the location has been found.
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
self.latPoint = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
self.lonPoint = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
NSLog(@"lat is %@ : lon is %@",self.latPoint, self.longPoint);
//Now you know the location has been found, do other things, call others methods here
}
John