在info.plist中加入:
//允许在前台使用时获取GPS的描述
定位权限:Privacy - Location When In Use Usage Description
//允许永久使用GPS描述
定位权限: Privacy - Location Always and When In Use Usage Description
如下图:
image.png然后再添加framework包,如下图:
image代码如下:
1,导入系统文件,代理:
import <CoreLocation/CoreLocation.h>
@interface MainViewController ()<CLLocationManagerDelegate>
2,声明全局变量
@interface MainViewController ()<CLLocationManagerDelegate>
{
CLLocationManager *locationmanager;//定位服务
NSString *currentCity;//当前城市
NSString *strlatitude;//经度
NSString *strlongitude;//纬度
}
3,声明方法:
//获取经纬度
[self getLocation];
4,
-(void)getLocation
{ //判断定位功能是否打开
if ([CLLocationManager locationServicesEnabled]) {
locationmanager = [[CLLocationManager alloc]init];
locationmanager.delegate = self;
[locationmanager requestAlwaysAuthorization];
currentCity = [NSString new];
[locationmanager requestWhenInUseAuthorization]; //设置寻址精度
locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
locationmanager.distanceFilter = 5.0;
[locationmanager startUpdatingLocation];
}
}
5,定位失败后的代理方法
pragma mark CoreLocation delegate (定位失败)
//定位失败后调用此代理方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{ //设置提示提醒用户打开定位服务
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"允许定位提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:nil];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:okAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
}
6,定位成功后的代理方法
pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
[locationmanager stopUpdatingHeading]; //旧址
CLLocation *currentLocation = [locations lastObject];
CLGeocoder *geoCoder = [[CLGeocoder alloc]init]; //打印当前的经度与纬度
NSLog(@"%f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude); //反地理编码
[geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark > * _Nullable placemarks, NSError * _Nullable error) { if (placemarks.count > 0) {
CLPlacemark placeMark = placemarks[0];
currentCity = placeMark.locality; if (!currentCity) {
currentCity = @"无法定位当前城市";
} /看需求定义一个全局变量来接收赋值/ NSLog(@"----%@",placeMark.country);//当前国家
NSLog(@"%@",currentCity);//当前的城市 // NSLog(@"%@",placeMark.subLocality);//当前的位置 // NSLog(@"%@",placeMark.thoroughfare);//当前街道 // NSLog(@"%@",placeMark.name);//具体地址
}
}];
}
网友评论