iOS如何获取当前地理位置

  1. 导入 CoreLocation 框架以及头文件
    #import <CoreLocation/CoreLocation.h>
  2. 创建CLLocationManager对象并设置代理
   <CLLocationManagerDelegate>
    // 初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置过滤器为无
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    // 取得定位权限,有两个方法,取决于你的定位使用情况
    // 一个是requestAlwaysAuthorization,一个是requestWhenInUseAuthorization
    // 这句话ios8以上版本使用。
    [_locationManager requestAlwaysAuthorization];
    // 开始定位
    [_locationManager startUpdatingLocation];
  1. 在iOS8以上的系统还需要在 plist 文件中添加以下key来配置
    Privacy - Location Always Usage Description
    Privacy - Location When In Use Usage Description

里面的值可以自己添加

  1. 如果想开启后台定位的话,需要按照以下步骤设置

     

    开启后台定位.png

  2. 在对应的代理方法中获取到我们需要的位置信息
    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
    在此代理方法中我们可以获取到当前位置的经纬度
    //获取经度
    //self.longitude.text = [NSString stringWithFormat:@"%lf", newLocation.coordinate.longitude];
    //获取维度
    //self.latitude.text = [NSString stringWithFormat:@"%lf", newLocation.coordinate.latitude];

获取当前位置所在的市信息

    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //获取当前城市
            NSString *city = placemark.locality;
            if (!city) {
                //注意:四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
                city = placemark.administrativeArea;
            }
            NSArray *array = [city componentsSeparatedByString:@"市"];
            NSString *cityStr = array[0];
            NSString * cityEncode = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)cityStr, NULL, NULL,  kCFStringEncodingUTF8 ));
            //这里我把获取到的地址信息利用NSUserDefaults保存起来,后面会用到
            NSMutableDictionary *dic = [NSMutableDictionary new];
            [dic setValue:cityEncode forKey:@"city"];
            [[NSUserDefaults standardUserDefaults] setObject:dic forKey:@"cityName"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        else if (error == nil && [array count] == 0) {
            NSLog(@"没有结果返回.");
        }
        else if (error != nil)  {
            //NSLog(@"An error occurred = %@", error);
        }
    }];
  1. 系统会在后台一直更新定位数据,如果只需要获取一次信息可以在信息获取完毕之后停止更新
    [manager stopUpdatingLocation];


 

发布了49 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_29680975/article/details/87606709