-1

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];
}
Mugs
  • 129
  • 10
  • 1
    Most likely because the location manager is asynchronous, and your NSLog call to print selt.latpoint and self.longpoint occurs before the location manager has had time to find and store the current location. move the NSLog statement to the didUpdateLocations method. – Woodstock Aug 06 '14 at 06:26

1 Answers1

1

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

Woodstock
  • 22,184
  • 15
  • 80
  • 118