用ios自带的 CLLocation实现定位功能

我做项目时需要用定位功能,当时考虑过 百度和高的. 由于功能模块比较单一,就用的苹果自带的定位.

直接粘贴复制到项目里就可以了;

 

第一步 : 导入头文件 

 #import

遵守代理 CLLocationManagerDelegate协议

创建 属性 @property (nonatomic, strong) CLLocationManager* locationManager;//定位


2. 直接调用这个方法 就可以 实现 定位功能

-(void)PositioningCity {

if([CLLocationManager locationServicesEnabled]){

if(!_locationManager){

self.locationManager = [[CLLocationManager alloc] init];

if([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){

[self.locationManager requestWhenInUseAuthorization];

[self.locationManager requestAlwaysAuthorization];

}

//设置代理

[self.locationManager setDelegate:self];

//设置定位精度

[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

//设置距离筛选

[self.locationManager setDistanceFilter:100];

//开始定位

[self.locationManager startUpdatingLocation];

//设置开始识别方向

[self.locationManager startUpdatingHeading];

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){

[_locationManager requestWhenInUseAuthorization];  //调用了这句,就会弹出允许框了.

}

}

}else{

UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您没有开启定位功能" preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

}];

[alertVC addAction:alert];

}

}


#pragma mark - CLLocationManangerDelegate


//定位成功以后调用

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

[self.locationManager stopUpdatingLocation];

CLLocation* location = locations.lastObject;

[self reverseGeocoder:location];

}


#pragma mark Geocoder

//反地理编码

- (void)reverseGeocoder:(CLLocation *)currentLocation {

CLGeocoder* geocoder = [[CLGeocoder alloc] init];

[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {

if(error || placemarks.count == 0){

NSLog(@"error = %@",error);

locationCity = @"南京";

}else{

CLPlacemark* placemark = placemarks.firstObject;

NSLog(@"placemark:%@",[[placemark addressDictionary] objectForKey:@"City"]);

NSString *cityStr = [[placemark addressDictionary] objectForKey:@"City"];

locationCity = [cityStr substringToIndex:cityStr.length - 1];//城市


//            [self  weatherHttplocation];

//            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"当前位置" message: [NSString stringWithFormat:@"placemark:%@",[placemark addressDictionary]]preferredStyle:UIAlertControllerStyleAlert];

//            UIAlertAction *alert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

//

//

//            }];

//            [alertVC addAction:alert];

//            [self]

}

}];

//        [self  weatherHttplocation ];

}

你可能感兴趣的:(用ios自带的 CLLocation实现定位功能)