iOS GPS位置決めCLLocationManagerは、現在位置座標の例コードを取得します。

2035 ワード

参照先: 
http://www.jianshu.com/p/ef6994767cbb
http://www.jianshu.com/p/f58be9373b6a
- (void)initLocationManager {
    if ([CLLocationManager locationServicesEnabled]) {
        if (self.locationManager == nil){
            self.locationManager = [[CLLocationManager alloc] init];
        }
        self.locationManager.delegate = self;
        self.locationManager.distanceFilter = 1.0;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [self.locationManager requestAlwaysAuthorization]; //     
            [self.locationManager requestWhenInUseAuthorization]; //     
        }
        
        [self.locationManager startUpdatingLocation];//      
    }
}
//        
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation * currentLocation = [locations lastObject];
    if (currentLocation != nil) {
        [self.locationManager stopUpdatingLocation];             //     
    }
    double altitude = currentLocation.altitude;                 //   
    double latitude = currentLocation.coordinate.latitude;
    double longitude = currentLocation.coordinate.longitude;
    
    NSLog(@"altitude:%f, latitude: %f, longitude:%f", altitude, latitude, longitude)
    
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"%@", error);
    if (error.code == kCLErrorDenied) {
        NSLog(@"%@", error);
    }
}
ios 8には設定キーが必要です。 info.plistに以下のキーを入れます。
<key>NSLocationWhenInUseUsageDescription</key>
<string>   GPS  ,         </string>
<key>NSLocationAlwaysUsageDescription</key>
<string>   GPS  ,         </string> 
keyのデータタイプはテスト結果によって、string(一部の文字列の説明)とbook(YES)のタイプが測位できるようです。