1、首先在plist表里邊添加Privacy - Location Usage Description和NSLocationWhenInUseUsageDescription(這個是在程序使用期間進行定位,如果需要一直獲取,添加NSLocationAlwaysUsageDescription),都為String類型
2、其次在.m中引入CoreLocation/CoreLocation.h頭文件,並且遵循CLLocationManagerDelegate代理。然后定義一個CLLocationManager對象,代碼如下:
#import "CoreLocation/CoreLocation.h" @interface ViewController ()<CLLocationManagerDelegate> @property (strong, nonatomic) CLLocationManager* locationManager; @end
3、開始定位的時候,首先判斷是否能定位
-(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.提醒用戶打開定位開關 } }
4、代理方法
- (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 = [[CLGeocoder alloc] init]; [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) { 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"]); } }]; }
5、定位失敗,調用此方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ if ([error code] == kCLErrorDenied){ //訪問被拒絕 } if ([error code] == kCLErrorLocationUnknown) { //無法獲取位置信息 } }:
warning!!!!!!!!!
如果打印錯誤信息為:Error Domain=kCLErrorDomain Code=0 "(null)"。進行如下操作:
Product -> Scheme -> Edit Scheme -> Options -> 把“ Allow Location Simulation ” 選項選中,並且設置下方的“default location”就可以了,不要讓這個選項為none