如何将纬度和经度坐标保存到nsstring,以便我可以在另一个函数中使用它。基本上,我只想显示从坐标中检索到的值,以传递给uilabel。
- (void)viewDidLoad
{
[super viewDidLoad];
[self getCurrentLocation];
NSLog(@"lat is %@ : lon is %@",self.latPoint, self.longPoint);
}
我试图用NSlog检索上面的内容并显示为null。我在我的.h文件中创建了两个NSString属性作为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];
}
答案 0 :(得分:1)
您看到的行为很可能是因为CLLocationManager
回调是异步的。您的NSLog调用打印self.latPoint
和self.longPoint
(最有可能)在位置管理员有时间查找并存储当前位置之前发生。
如果您将NSLog(@"lat is %@ : lon is %@",self.latPoint, self.longPoint);
语句移至didUpdateLocations
方法,则只要位置管理员找到(并更新)您当前的位置,您就会看到它被调用。
您只需要对CLLocationManager
回调做出反应,而不是尝试确定何时找到该位置。
- (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
}
约翰