简体   繁体   English

iOS CLLocation - 获取ViewDidLoad上的位置

[英]iOS CLLocation - getting the location on ViewDidLoad

This is probably going to be something simple I'm missing, but I have the location services set up as so (shortened for clarity): 这可能是我想要的简单事情,但我已经设置了位置服务(为了清晰起见缩短了):

- (void)viewDidLoad
{
    self.locationManager = [[[CLLocationManager alloc] init] autorelease];
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"%@",newLocation.coordinate.latitude);
    NSLog(@"%@",newLocation.coordinate.longitude);
}

which works fine and gives me a stream of location data to the log. 工作正常,并给我一个位置数据流到日志。

But what I want is to be able to get the current location immediately in the ViewDidLoad, as I only need it once, not a constant update - it's only to pinpoint a "nearest" amenity so I can report back to the user. 但我想要的是能够立即在ViewDidLoad中获取当前位置,因为我只需要它一次,而不是一次不断的更新 - 它只是为了找到“最近”的便利设施,所以我可以向用户报告。 I've tried adding: 我试过添加:

self.locationLat = [self.locationManager location].coordinate.latitude;
self.locationLng = [self.locationManager location].coordinate.longitude;

to the ViewDidLoad immediately after startUpdatingLocation, but they always come out as null. 在startUpdatingLocation之后立即到ViewDidLoad,但它们总是以null形式出现。 Is there something else I have to call to get that data once it's running? 还有什么我需要调用才能在运行后获取数据吗?

Thanks 谢谢

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    /*report to user*/
    [self.locationManager stopUpdatingLocation];
}

So you will get location once and then stop updating it. 因此,您将获得一次位置,然后停止更新它。

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    [manager stopUpdatingLocation];
    NSLog(@"%@",newLocation.coordinate.latitude);
    NSLog(@"%@",newLocation.coordinate.longitude);
}

You will only get the values in 您只能获得值

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

no other function is available to get location values.. so the fastest you will get values is when this function is called first... 没有其他功能可用于获取位置值..因此,您将获得最快的值是在首次调用此函数时...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM