// 首先导入头文件#import<CoreLocation/CoreLocation.h>
/** * 定位管理者,全局变量强引用,防止销毁 */
@property
(nonatomic ,strong) CLLocationManager *mgr;
// 2.成为CoreLocation管理者的代理监听获取到的位置self.mgr.delegate =self;
1需要得到用户的授权
ios8以上需要用户自己开启授权
在iOS8中不仅仅要主动请求授权,而且必须再info.plist文件中配置一项属性才能弹出授权窗口
- NSLocationWhenInUseDescription,允许在前台获取GPS的描述
- NSLocationAlwaysUsageDescription,允许在后台获取GPS的描述
- iOS 9
- 如果想要在后台定位,除了配置
NSLocationAlwaysUsageDescription(前后台定位)
外,还需要手动设置allowsBackgroundLocationUpdates = YES
-
②开始用户定位
- (void)startUpdatingLocation;
③停止用户定位
- (void) stopUpdatingLocation;
③设置当用户移动多少米,重新定位
- self.mgr.distanceFilter = 50;
④设置获取位置的精确度
- 越精确就越耗电
/* kCLLocationAccuracyBestForNavigation 最佳导航 kCLLocationAccuracyBest; 最精准 kCLLocationAccuracyNearestTenMeters; 10米 kCLLocationAccuracyHundredMeters; 百米 kCLLocationAccuracyKilometer; 千米 kCLLocationAccuracyThreeKilometers; 3千米 */ self.mgr.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
初始化CLLocationManager 设置代理事件
locationmanager =[[CLLocationManageralloc]init];
locationmanager.delegate =self;
//次代码只为判断该程序是否开启定位
CLAuthorizationStatus status =[CLLocationManagerauthorizationStatus];
if (status ==kCLAuthorizationStatusNotDetermined) {
NSLog(@"等待授权");
}elseif(status ==kCLAuthorizationStatusAuthorizedAlways ||
status == kCLAuthorizationStatusAuthorizedWhenInUse)
{
NSLog(@"授权成功");
}else{
NSLog(@"没有该权限");
}
如果iOS系统为8.0以下 那么直接设置允许
if([[[UIDevicecurrentDevice] systemVersion]doubleValue]>8.0){
//这里是设置只有在运行该程序的时候使用定位系统,只有ios8才能设置此
[locationmanagerrequestWhenInUseAuthorization];
}
//定位的频率也就是多少米定位一次
_locationmanager.distanceFilter =20;
//定位的精度
_locationmanager.desiredAccuracy =kCLLocationAccuracyBest;
//4.开始更新位置
[_locationmanagerstartUpdatingLocation];
//该获取地理位置信息方法只有在手机上才可以测试
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
NSLog(@"find you");
//获取用户最后的位置
CLLocation *location = [locationslastObject];//位置信息
CLLocationCoordinate2D coordinate = location.coordinate;//经纬度
//打印出经纬度
NSLog(@"lon:%f,lat:%f",coordinate.longitude,coordinate.latitude);
//有时候找到用户位置后就不需要更新了
[_locationmanagerstopUpdatingLocation];//停止位置更新
//顺带添加一个反编码地理位置 但是不是太准确
CLLocation *mycll = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
//创建位置
CLGeocoder *mycoder =[[CLGeocoder alloc]init];
[mycoder reverseGeocodeLocation:mycll completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (!error&& [placemarks count] > 0) {
NSDictionary *dict =[[placemarks objectAtIndex:0]addressDictionary];
NSLog(@"street address: %@",
//记录地址
[dict objectForKey:@"Street"]);
}
}];
}
-(void)locationManager:(nonnullCLLocationManager *)manager didFailWithError:(nonnullNSError *)error{
NSLog(@"not find");
}