核心位置无法在viewDidLoad中获取数据 [英] Core Location can't get data in viewDidLoad

查看:83
本文介绍了核心位置无法在viewDidLoad中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的iOS应用程序,该应用程序检索位置信息,然后使用该位置请求Yahoo Weather。

I wrote a simple iOS application that retrieves location information and then uses the location to request Yahoo Weather.

问题是,即使我在viewDidLoad中调用核心位置,它也不会立即给我结果。

The problem is that even when I call the Core Location in the viewDidLoad, it won't give me the result immediately.

为什么我不能获取位置信息?

So why can't I get the location information?

如何在viewDidLoad中获取位置信息?

How can I get the location information in viewDidLoad?

当前的伪代码如下:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.locManager = [[CLLocationManager alloc] init];
    self.locManager.delegate = self;

    self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locManager.distanceFilter = 100;
    [self.locManager startUpdatingLocation];

    //won't get the current location right now, so the output will be null
    NSLog(@"Current Location Longitude: %@", self.longitudeString);
    NSLog(@"Current Location Latitude: %@", self.latitudeString);
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *newLocation = [locations lastObject];
    self.longitudeString = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    self.latitudeString = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}


推荐答案

位置更新不作为正如您所期望的那样,您需要立即等待几秒钟(2-3或更长时间)以获取精确的位置更新。如果要在viewDidLoad中包含位置数据,则应在调用ViewController之前初始化位置管理器(并调用startUpdatingLocation)(因为不能保证在viewDidLoad中包含位置数据)。

Location updates are not provided as instantly as you are expecting, you need to wait few seconds (2-3 or may be more) to get precise location update. If you want to have location data in viewDidLoad then you should init your location manager (and call startUpdatingLocation) before invoking the ViewController (since then it is not guaranteed that you will have location-data in viewDidLoad).

这篇关于核心位置无法在viewDidLoad中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆