zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

iOS原生定位和反编码

2023-06-13 09:15:10 时间

经常碰到需要获取当前地址的需求,iOS原生方法就可以解决。

导入头文件

#import <CoreLocation/CoreLocation.h>

@property (nonatomic, strong) CLLocationManager *lcManager

开始请求定位

if ([CLLocationManager locationServicesEnabled]) { 

// 创建位置管理者对象 

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

self.lcManager.delegate = self; // 设置代理 

// 设置定位距离过滤参数 (当本次定位和上次定位之间的距离大于或等于这个值时,调用代理方法) 

self.lcManager.distanceFilter = 100;

self.lcManager.desiredAccuracy = kCLLocationAccuracyBest; // 设置定位精度(精度越高越耗电)

[self.lcManager requestWhenInUseAuthorization];//这句很关键!!!

[self.lcManager startUpdatingLocation]; // 开始更新位置

}else{ 

//没开启,做其他提醒 

}

代理:CLLocationManagerDelegate

代理方法: `

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
NSLog(@"定位到了");

CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:[locations firstObject] completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError * _Nullable error) {
    
    CLPlacemark *place = [placemarks firstObject];
	//place包含了地理信息
}];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(@"获取定位失败");
}