iOS获取当前定位位置经纬度及城市
.m
#import <CoreLocation/CoreLocation.h>
@interface HomeViewController ()<CLLocationManagerDelegate>{
NSString* currentCity;//当前城市
}
@property (strong, nonatomic) CLLocationManager* locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self startLocation];
}
#pragma mark---------判断定位操作是否被允许-----------
-(void)startLocation{
if ([CLLocationManager locationServicesEnabled]) {//判断定位操作是否被允许
self.locationManager= [[CLLocationManager alloc]init];
self.locationManager.delegate = self;//遵循代理
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = 10.0f;
[_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据(iOS8以上版本定位需要)
[self.locationManager startUpdatingLocation];//开始定位
}else{//不能定位用户的位置的情况再次进行判断,并给与用户提示
//1.提醒用户检查当前的网络状况
//2.提醒用户打开定位开关
UIAlertController* alertVC = [UIAlertControlleralertControllerWithTitle:@"允许\"定位\"提示"message:@"请在设置中打开定位"preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertActionactionWithTitle:@"打开定位"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {
//打开定位设置
NSURL*settingsURL = [NSURLURLWithString:UIApplicationOpenSettingsURLString];
[[UIApplicationsharedApplication]openURL:settingsURL];
}];
UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[alertVCaddAction:cancel];
[alertVCaddAction:ok];
[self presentViewController:alertVC animated:YES completion:nil];
}
}
#pragma mark---------定位成功---------
- (void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations{
//当前所在城市的坐标值
CLLocation*currLocation = [locations lastObject];
// NSLog(@"当前经度=%f 当前纬度=%f 当前高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);
//根据经纬度反向地理编译出地址信息
CLGeocoder* geoCoder = [[CLGeocoderalloc]init];
[geoCoderreverseGeocodeLocation:currLocationcompletionHandler:^(NSArray*placemarks,NSError*error) {
if(placemarks.count>0) {
CLPlacemark*placeMark = placemarks[0];
currentCity= placeMark.locality;
if(!currentCity) {
currentCity=@"无法定位当前城市";
}
// NSLog(@"%@",currentCity); //这就是当前的城市
// NSLog(@"%@",placeMark.name);//具体地址: xx市xx区xx街道
//
// for (CLPlacemark * placemark in placemarks) {
//
// NSDictionary *address = [placemark addressDictionary];
//
// // Country(国家) State(省) City(市)
// NSLog(@"#####%@",address);//所有返回属性
//
// NSLog(@"%@", [address objectForKey:@"Country"]);
//
// NSLog(@"%@", [address objectForKey:@"State"]);
//
// NSLog(@"%@", [address objectForKey:@"City"]);
//
// }
}];
}
#pragma mark---------定位失败-----------
-(void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error{
if([errorcode] ==kCLErrorDenied){
//访问被拒绝
ALERT(@"提示", @"位置访问被拒绝");
}
if ([error code] == kCLErrorLocationUnknown) {
//无法获取位置信息
ALERT(@"提示", @"无法获取位置信息");
}
}