CLLocationManager定位当前位置

1、导入CoreLocation.h 头文件,然后声明专属的管理者对象,遵守代理CLLocationManagerDelegate

@property(nonatomic,strong)CLLocationManager *locationManager;

2、在viewdidload里面判断当前设备定位服务是否打开了,然后设置代理和精度

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

//初始化管理对象

CLLocationManager *locationManager = [[CLLocationManager alloc]init];

self.locationManager = locationManager;

//判断当前设备定位服务是否打开

if (![CLLocationManager locationServicesEnabled]) {

NSLog(@"设备尚未打开定位服务");

}

//判断当前设备版本大于iOS8以后的话执行里面的方法

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

[locationManager requestAlwaysAuthorization];

[locationManager  requestWhenInUseAuthorization];

}

//设置代理

locationManager.delegate = self;

//设置定位精度

locationManager.desiredAccuracy = kCLLocationAccuracyBest;

////设置定位的频率,这里我们设置精度为10,也就是10米定位一次

CLLocationDistance distance = 10;

//给精度赋值

locationManager.distanceFilter = distance;

//开始启动定位

[locationManager startUpdatingLocation];

}


3、配置info.plist文件,把下面两个属性加到文件中去,并且确定xcode是否联网

NSLocationAlwaysUsageDescription

NSLocationWhenInUseUsageDescription


CLLocationManager定位当前位置_第1张图片


4、实现代理方法进行定位当前的位置,获取到经纬度

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

5、通过反地理编码进行中文的输出即可

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


6.不定位的时候应该停止定位

[self.locationManager stopUpdatingLocation];

//定位获取当前的经纬度

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray*)locations {    CLLocation *location = [locations lastObject];    NSLog(@"%@",location.timestamp);    CLLocationCoordinate2D coordinate = location.coordinate;    NSLog(@"%f    ,%f", coordinate.latitude,coordinate.longitude );        CLGeocoder *geocoder = [[CLGeocoder alloc]init];        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray* _Nullable placemarks, NSError * _Nullable error) {

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

NSLog(@"%@",error);

return ;

}

for (CLPlacemark *placemark in placemarks) {

self.addressTextLabel.text = placemark.locality;

NSLog(@"%@",placemark.locality);

}

}];

[self.locationManager stopUpdatingLocation];

}



CLLocationManager定位当前位置_第2张图片
CLLocationManager定位当前位置_第3张图片

你可能感兴趣的:(CLLocationManager定位当前位置)