ios開發之 -- 呼叫系統定位獲取當前經緯度與地理資訊
阿新 • • 發佈:2019-01-31
在info.plist中加入:
//允許在前臺使用時獲取GPS的描述
定位許可權:Privacy - Location When In Use Usage Description
//允許永久使用GPS描述
定位許可權: Privacy - Location Always Usage Description
如下圖:
然後再新增framework包,如下圖:
程式碼如下:
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);//具體地址 } }]; }
列印如下: