獲取Location

1.鏈接一個二進制的庫用來定位 CoreLocationios

Build Phases中加號添加ui

2.對於ios8.0以上的須要配置編碼

  NSLocationWhenInUseUsageDescriptionatom

  NSLocationAlwaysUsageDescriptionspa

3.導入頭文件代理

  #import <CoreLocation/CoreLocation.h>導入這一個頭文件其餘的都導進來了code

4.建立一個CLLocationManager對象,來管理定位orm

  @property (nonatomic,strong) CLLocationManager * locationManager;對象

  @property (nonatomic,strong) CLGeocoder * geoCoder;blog

5.服從代理<CLLocationManagerDelegate>

  @interface ViewController : UIViewController<CLLocationManagerDelegate>

6.判斷設備是否支持定位

  if ([CLLocationManager locationServicesEnabled])

7.8.0以上必須手動請求認證受權

   if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {

            [self.locationManager requestWhenInUseAuthorization];} 

8.設置好定位

  - (void)viewDidLoad {

      [super viewDidLoad];    

      if ([CLLocationManager locationServicesEnabled]) {

          self.locationManager = [[CLLocationManager alloc]init];

          self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

          self.locationManager.delegate = self;

          if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {

              [self.locationManager requestWhenInUseAuthorization];

          }  

      }

  }

9.開始定位

  [self.locationManager startUpdatingLocation];

10.實現代理方法,爲之不斷更新就不斷調用這個方法

  -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{    

      //暫停更新,不要一直處於更新狀態太費電

      [self.locationManager stopUpdatingLocation];

      //獲取最新location

      CLLocation * newLocation = [locations lastObject];

      //location反編碼  

      self.geoCoder = [[CLGeocoder alloc]init];

      [self.geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {

         //獲取placeMark

            CLPlacemark * placemark = [placemarks lastObject];

          self.locationLable.text = [NSString stringWithFormat:@"%@-%@-%@-%@\n%@-%@", placemark.country, placemark.administrativeArea, placemark.locality, placemark.subLocality, placemark.thoroughfare, placemark.name];

      }];   

  }

相關文章
相關標籤/搜索