首先导入CoreLocation.framework,然后再引入头文件#import
定义属性
@property (nonatomic , strong)CLLocationManager *locationManager;
初始化定位服务
#pragma mark - 私有方法
///初始化定位服务
- (void)settupLocation
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
if ([CLLocationManager locationServicesEnabled] &&
[CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
//定位功能可用,开始定位
[self.locationManager startUpdatingLocation];
} else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
//请求授权
[self.locationManager requestWhenInUseAuthorization];
} else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied
|| [CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted){
}
if (self.schoolStr.length < 2) {
// 开始定位
[_locationManager startUpdatingLocation];
}
}
然后使用代理 CLLocationManagerDelegate
#pragma mark - <CLLocationManagerDelegate>
///成功定位
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
//经纬度信息
CLLocation *location = [locations lastObject];
//反地理编码
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//编码成功
if (!error && placemarks.count > 0) {
//获取地址对象
CLPlacemark *address = placemarks.firstObject;
//获取城市名称
NSMutableString *city = [NSMutableString stringWithString:address.locality];
if ([city containsString:@"市"]) {
[city deleteCharactersInRange:[city rangeOfString: @"市"]];
}
//显示定位信息
self.schoolStr = city;
[self.tableView reloadData];
//停止定位
[self.locationManager stopUpdatingLocation];
} else {
//编码失败
}
}];
}
在Info.plist文件中添加如下配置:
(1)NSLocationAlwaysUsageDescription
(2)NSLocationWhenInUseUsageDescription