代码之家  ›  专栏  ›  技术社区  ›  BlackM

在iOS中使用CLLocation管理器获取一次坐标

  •  1
  • BlackM  · 技术社区  · 12 年前

    我正在使用此代码获取坐标:

    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.delegate = self;
    [_locationManager startUpdatingLocation];
    

    然后我使用

    - (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
    {
    
    _currentLocation = [locations lastObject];
    
    
    //Doing some stuff
    
    //I am using stopUpdatingLocation but this delegate is called a lot of times
    [_locationManager stopUpdatingLocation];
    
    
    
     }
    

    实际上,我想获得一次坐标,因为我想避免在didUpdateLocation中多次执行代码。我该怎么做?

    1 回复  |  直到 12 年前
        1
  •  0
  •   Rowan Freeman    12 年前

    之所以会出现这种情况,是因为位置管理器多次触发其更新,从而逐渐获得更准确的位置结果。

    停止这种情况的一种方法是简单地使用布尔值

    BOOL _hasUpdatedUserLocation = NO;
    
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
        if (!_hasUpdatedUserLocation) {
            _hasUpdatedUserLocation = YES;
            ... // other code
        }
    }
    

    或者,您可以杀死代理:

    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
        [locationManager setDelegate:nil];
        ... // other code
    }