iOS 自带定位最新获取 街区名字 、街道名字、城市名字、省份等,并获取当经纬度。

首先,我们又带.h文件导入官方的头文件

#import 

接下来要遵守它的协议

接下来在创建它的对象

@property (strong, nonatomic) CLLocationManager* locationManager;

接下来我们要在.m文件中,写入以下代码

//开始定位
-(void)startLocation{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100.0f;
    if ([[[UIDevice currentDevice]systemVersion]doubleValue] > 8.0){//iOS 8.0以后调用
        [self.locationManager requestWhenInUseAuthorization];
    }
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {//iOS 8.0以后调用
        _locationManager.allowsBackgroundLocationUpdates = YES;
    }
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
         case kCLAuthorizationStatusNotDetermined:
            if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [self.locationManager requestWhenInUseAuthorization];
            }
        break;
        default:
        break;
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { 
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    NSLog(@"旧的经度:%f,旧的纬度:%f",oldCoordinate.longitude,oldCoordinate.latitude);
    [manager stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray * _Nullable placemarks, NSError * _Nullable error) {
         for (CLPlacemark *place in placemarks) {
//           NSLog(@"name,%@",place.name);                       // 位置名         
//           NSLog(@"thoroughfare,%@",place.thoroughfare);       // 街道
//           NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
//           NSLog(@"locality,%@",place.locality);               // 市
//           NSLog(@"subLocality,%@",place.subLocality);         // 区
//           NSLog(@"country,%@",place.country);                 // 国家
             if ([JudgeIDAndBankCard isEmptyOrNull:place.locality]) {
                 _gpsCityName=@"定位失败";
             }
             WRITE_DATA(place.locality, @"CITY_JC_NAME");
         }
    }];
}

这些都完成后,我们还要做一件非常重要的事情,我们要在info.plist文件配置一下文件

info.plist文件也需要加两个字段:

Privacy - Location Always Usage Description:类型可以设置为字符串
Privacy - Location When In Use Usage Description :类型可以设置为字符串

iOS 自带定位最新获取 街区名字 、街道名字、城市名字、省份等,并获取当经纬度。_第1张图片

 

 

 

你可能感兴趣的:(苹果,iOS,OC)