Ios NSLocation位置保持更新

Ios NSLocation位置保持更新,ios,objective-c,Ios,Objective C,我只尝试获取当前位置一次,但是didUpdateToLocation被反复调用。我正在调用viewDidLoad中的getCurrentLocation。我怎么能让它只得到一次位置 - (IBAction)getCurrentLocation:(id)sender { locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationM

我只尝试获取当前位置一次,但是didUpdateToLocation被反复调用。我正在调用viewDidLoad中的getCurrentLocation。我怎么能让它只得到一次位置

- (IBAction)getCurrentLocation:(id)sender {
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [locationManager startUpdatingLocation];
}


#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
    UIAlertView *errorAlert = [[UIAlertView alloc]
                               initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil) {
        for (int i = 0; i < [storesArray count]-1; i++) {            
            CLLocationDegrees latitude = [[[storesArray objectAtIndex:i] valueForKey:@"lat"] doubleValue];
            CLLocationDegrees longitude = [[[storesArray objectAtIndex:i] valueForKey:@"long"] doubleValue];

            CLLocation *checkPosition = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

            CLLocationDistance distance = [checkPosition distanceFromLocation:currentLocation];

            float distanceInKm = distance / 1000;

            if (distanceInKm > 5) {
                NSLog(@"%@", distanceInKm);
            }
        }
    }
}
你需要打电话

[locationManager stopUpdatingLocation];
参见:

只要代码不再需要接收与位置相关的事件,就调用此方法。禁用事件传递使接收器可以选择禁用适当的硬件,从而在没有客户端需要位置数据时节省电源。通过再次调用startUpdatingLocation方法,始终可以重新启动位置更新的生成


当你得到你想要的东西时,停止更新位置如何?好的,似乎是可行的,但奇怪的是,当[storesArray count]-1=2时,我返回了4个距离。它应该只返回3个距离。我不知道storesArray是什么。这是你没有分享的代码,我们如何帮助你?但是,在didUpdateToLocation的实现中,您可能应该首先调用StopUpdateLocation,否则,每次传感器获得更准确的位置或位置根据您配置位置管理器的方式发生显著变化时,都会调用StopUpdateLocation。它似乎仍然运行for循环两次为什么?我认为我最新评论的第二部分回答了这个问题。只要传感器得到位置更新,而您还没有调用StopUpdateLocation,就会继续调用didUpdateToLocation。