iOS - 定位功能/获取当前位置信息的实现

本文比较简单,只是获取到当前的位置信息...

在需要定位的控制器 .m 里面,添加如下代码:


#import"ViewController.h"

#import<CoreLocation/CoreLocation.h>


@interface ViewController()<CLLocationManagerDelegate>


@property(nonatomic,strong)CLLocationManager*manager;


@end


@implementationViewController


- (void)viewDidLoad {

    [superviewDidLoad];

   // do anythings you want to do...

    

    [self getCurrentLocation];

    

 }


- (void)getCurrentLocation {

   //    locationServicesEnabled这个是判断当前设备的定位服务是否可用

   if(![CLLocationManagerlocationServicesEnabled]){

       NSLog(@"bu ke yong");

       return;

    }

   NSLog(@"ke yong");

   //    CLLocationManager这个类是用来定位的

   self.manager= [[CLLocationManageralloc]init];

   //   间隔多少米去重新定位

   self.manager.distanceFilter=10;

    //  这个属性是设计定位的精确度

   //    kCLLocationAccuracyBest这个是最好的精确度

   self.manager.desiredAccuracy=kCLLocationAccuracyBest;

   //   设置代理

   self.manager.delegate=self;

    

    //   如果当前设备大于等于8.0做一下特殊设置

   if([[UIDevicecurrentDevice].systemVersionfloatValue]>=8.0)

    {

        [self.managerrequestAlwaysAuthorization];

       //        [manager requestWhenInUseAuthorization];

    }

   if([[UIDevicecurrentDevice].systemVersionfloatValue]>=9.0)

    {

        [self.managerallowsBackgroundLocationUpdates];//允许后台定位更新

    }

   //   开始定位

    [self.managerstartUpdatingLocation];

    

    

}


//这个代理方法是在定位失败的时候会调用

-(void)locationManager:(CLLocationManager*)manager didFailWithError:(nonnullNSError*)error{

   NSLog(@"==error===>>>%@",error.localizedDescription);

}

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

   CLLocation*location = [locationslastObject];


   CLGeocoder*geocoder = [[CLGeocoderalloc]init];

    [geocoderreverseGeocodeLocation:locationcompletionHandler:^(NSArray<CLPlacemark*> *_Nullableplacemarks, NSError*_Nullableerror) {

       //        CLPlacemark这个类里面装的是你当前定位到的那个地点的信息

       CLPlacemark*mark = [placemarksfirstObject];

       //        mark.country

       //          mark.location.coordinate

        

        //看到输出之后,我想你什么都明白了吧。。。

          NSLog(@"======>>%@------%@=====>>>%@",mark.locality,mark.name,mark.addressDictionary);

    }];

}



OK,到此结束...



版权声明:本文为Q_Q33757152原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。