整体思路:
获取定位需要用到的是CoreLocation.framework里面的CLLocationManager类,设置了详细的参数和代理后,获取成功和失败的信息都会在代理方法里面体现。
详细步骤:
1.在系统定位权限打开的情况下再进行操作
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];
}
2.获取定位成功后调用的代理方法
-(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(@"%@",currentCity);
NSLog(@"%@",placeMark.country);//国家
}
}];
}
3.获取定位失败后调用的代理方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
//去设置中心打开定位服务
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}