1.连接一个二进制的库用来定位 CoreLocation
Build Phases中加号添加
2.对于ios8.0以上的需要配置
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
3.导入头文件
#import <CoreLocation/CoreLocation.h>导入这一个头文件其他的都导进来了
4.创建一个CLLocationManager对象,来管理定位
@property (nonatomic,strong) CLLocationManager * locationManager;
@property (nonatomic,strong) CLGeocoder * geoCoder;
5.服从代理<CLLocationManagerDelegate>
@interface ViewController : UIViewController<CLLocationManagerDelegate>
6.判断设备是否支持定位
if ([CLLocationManager locationServicesEnabled])
7.8.0以上必须手动请求认证授权
if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {
[self.locationManager requestWhenInUseAuthorization];}
8.设置好定位
- (void)viewDidLoad {
[super viewDidLoad];
if ([CLLocationManager locationServicesEnabled]) {
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {
[self.locationManager requestWhenInUseAuthorization];
}
}
}
9.开始定位
[self.locationManager startUpdatingLocation];
10.实现代理方法,为之不断更新就不断调用这个方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
//暂停更新,不要一直处于更新状态太费电
[self.locationManager stopUpdatingLocation];
//获取最新location
CLLocation * newLocation = [locations lastObject];
//将location反编码
self.geoCoder = [[CLGeocoder alloc]init];
[self.geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//获取placeMark
CLPlacemark * placemark = [placemarks lastObject];
self.locationLable.text = [NSString stringWithFormat:@"%@-%@-%@-%@ %@-%@", placemark.country, placemark.administrativeArea, placemark.locality, placemark.subLocality, placemark.thoroughfare, placemark.name];
}];
}