NSLocation位置不断更新

时间:2014-07-09 12:40:19

标签: ios objective-c

我试图只获取当前位置一次,但是didUpdateToLocation被反复调用。我在getCurrentLocation中呼叫viewDidLoad。我怎么才能让它获得一次位置?

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

1 个答案:

答案 0 :(得分:0)

您需要致电

[locationManager stopUpdatingLocation];

比照official doc

  

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