如何在ios中获取一次位置

时间:2017-01-12 08:59:35

标签: ios cllocationmanager cllocation

如何在ios应用中仅获取一次该位置。

2 个答案:

答案 0 :(得分:3)

获取您的位置后,停止更新位置管理器并释放locationManager,因为您不再需要locationManager。

[self.locationManager stopUpdatingLocation];
self.locationManager.delegate = nil;
self.locationManager = nil;

答案 1 :(得分:0)

在ios 9及以上版本中我们有一个方法[locationManagerInstance requestLocation]。但是,由于该位置是最新且最好的,因此回拨委托方法需要将近10秒钟。

换句话说(对于早期的ios9版本),您仍然可以使用旧方法[locationManagerInstance startUpdatingLocation]来获取直接位置,还可以验证时间戳以获得最佳准确度。

以下是我用于获取位置的代码。为locationManager实例创建全局引用。

@interface ViewController ()
{
    CLLocationManager *locationManager;
}

在your.m文件中实现这些实用程序方法

-(BOOL)canUseLocationManager{
    if(([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) || ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)){
        return YES;
    }
    return NO;
}

-(void) getCurrentLocation {
    locationManager.delegate = self;
    // ios 9 and above versions only 
    //[locationManager requestLocation]; // This may take more time when compare to alternate method
    // ios 2 and later versions can use this method
    [locationManager startUpdatingLocation];
}

-(void) stopGettingCurrentLocation {
    [locationManager stopUpdatingLocation];
}

实施位置服务代表

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
        [self doneCheckingAccessStatusForLocation];
    }
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    [manager stopUpdatingLocation];
    locationManager.delegate = nil; 
    /* Clean the locationManager instance if you don't need*/
    //locationManager = nil;
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{

    [manager stopUpdatingLocation];
    locationManager.delegate = nil;

    CLLocation* location = [locations lastObject];
    NSDate* eventDate = location.timestamp;

    /* Implement your business logics here */
    /* Clean the locationManager instance if you don't need*/
    //locationManager = nil;
}

创建位置管理器实例并启动提取位置的最终方法

-(void)checkForLocationService{
    if(!locationManager){
        locationManager = [[CLLocationManager alloc] init];
        locationManager.distanceFilter = kCLDistanceFilterNone;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    }
    locationManager.delegate = self;
    if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
        [locationManager requestWhenInUseAuthorization];
    }else{
        [self doneCheckingAccessStatusForLocation];
    }

}

-(void)doneCheckingAccessStatusForLocation{
    if([self canUseLocationManager]){
        [self getCurrentLocation];
    }
}

调用checkForLocationService方法并在成功和失败委托方法上实现逻辑。

[self checkForLocationService];