美文网首页iOS 开发总结
【OC】CLLocationManager原生定位

【OC】CLLocationManager原生定位

作者: Richard_Wei | 来源:发表于2017-05-27 09:42 被阅读0次

    当遇到定位需求,且项目无需引入高德、百度等地图SDK时,采用系统自带定位方法和反地理解析,可以很容易获取用户位置。

    typedef void(^GetLocationSuccessBlock)(NSString *cityName);
    
    @property (nonatomic ,strong) GetLocationSuccessBlock getLocationSuccess;
    @property (nonatomic ,strong) CLLocationManager *locationManager;
    
    /// 开始定位
    - (void)getCurrentLocationSuccess:(GetLocationSuccessBlock)successBlock{
        
        self.getLocationSuccess = successBlock;
        
        [self initializeLocationService];
    }
    
    - (void)initializeLocationService {
        // 初始化定位管理器
        _locationManager = [[CLLocationManager alloc] init];
        // 设置代理
        _locationManager.delegate = self;
        // 设置定位精确度到米
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 设置过滤器为无
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        // 开始定位
        // 取得定位权限,有两个方法,取决于你的定位使用情况
        // 一个是requestAlwaysAuthorization,一个是requestWhenInUseAuthorization
        [_locationManager requestWhenInUseAuthorization];//这句话ios8以上版本使用。
        [_locationManager startUpdatingLocation];
    }
    
    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
        // 获取当前所在的城市名
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        //根据经纬度反向地理编译出地址信息
        [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
            if (array.count > 0){
                CLPlacemark *placemark = [array objectAtIndex:0];
                //将获得的所有信息显示到label上
                
                //获取城市
                NSString *city = placemark.locality;
                if (!city) {
                    //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
                    city = placemark.administrativeArea;
                }
                NSLog(@"city = %@", city);
                
                if (self.getLocationSuccess) {
                    self.getLocationSuccess(city);
                }
            }
            else if (error == nil && [array count] == 0)
            {
                NSLog(@"No results were returned.");
                if (self.getLocationSuccess) {
                    self.getLocationSuccess(@"定位失败");
                }
            }
            else if (error != nil)
            {
                NSLog(@"An error occurred = %@", error);
                if (self.getLocationSuccess) {
                    self.getLocationSuccess(@"定位失败");
                }
            }
        }];
        //系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
        [manager stopUpdatingLocation];
    }
    

    相关文章

      网友评论

        本文标题:【OC】CLLocationManager原生定位

        本文链接:https://www.haomeiwen.com/subject/nbgffxtx.html