Core Location can't get data in viewDidLoad

2019-09-17 06:42发布

问题:

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