iOS:点击按钮获取坐标,然后停止所有定位服务

iOS:点击按钮获取坐标,然后停止所有定位服务,ios,core-location,Ios,Core Location,现在,我有了它,所以当点击一个按钮时,它会启动位置服务,设置纬度/经度变量。但位置仍然在后台运行 我希望是这样,当我点击一个按钮,它找到了纬度/经度,所有的定位服务停止 这是我目前拥有的 - (IBAction)startButton:(id)sender { locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationMana

现在,我有了它,所以当点击一个按钮时,它会启动位置服务,设置纬度/经度变量。但位置仍然在后台运行

我希望是这样,当我点击一个按钮,它找到了纬度/经度,所有的定位服务停止

这是我目前拥有的

- (IBAction)startButton:(id)sender {

    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [locationManager startUpdatingLocation];
    NSLog(@"%@", [self lat]);
}

- (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) {
        [self setLat:[NSString stringWithFormat:@"%.6f", currentLocation.coordinate.latitude]];
    }
}
另一个问题是,如果我立即尝试检索lat属性的值,它将返回null,很可能是因为查找位置需要一两秒钟

因此,在设置lat/long属性之前,我还需要停止运行任何进一步的代码。例如,在找到纬度/经度之前,如何停止运行
otherFunction

- (IBAction)startButton:(id)sender {

    [self updateLocation];
    [self otherFunction];
}

- (void)updateLocation
{
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [locationManager startUpdatingLocation];
}

- (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) {
        [self setLat:[NSString stringWithFormat:@"%.6f", currentLocation.coordinate.latitude]];
[locationManager stopUpdatingLocation]
    }
}

如有任何帮助/想法,将不胜感激

在上一个函数中,验证currentLocation不是nil后,应检查currentLocation的准确性,然后调用setLat:函数,然后停止更新位置。有关更多详细信息,请参阅本文:


调用
[locationManager StopUpdatengLocation]
应该会停止它。您可以检查
lat
值(和
longitude
)以了解何时停止。你尝试了什么?@Larme:是的,这很有效,但是关于我的第二段代码,在设置lat/long之前,我如何阻止
[self-otherFunction]
运行?当你得到位置时调用otherFunction(即,就在您停止更新位置之后。@Larme:otherFunction必须由按钮触发。Edit:可能不是,可能结构有所不同