Core Location can't get data in viewDidLoad

自作多情 提交于 2019-12-24 22:33:22

问题


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

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?

How can I get the location information in viewDidLoad?

The pseudocode currently is something like:

- (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];
}

回答1:


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).



来源:https://stackoverflow.com/questions/25855381/core-location-cant-get-data-in-viewdidload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!