1、添加corelocation库,这个定位都要用到的,系统自带的
2、 #import <CoreLocation/CoreLocation.h>
3、添加CLLocationManagerDelegate定位代理
4、实例化定位管理器
_locationManager = [[CLLocationManageralloc] init];
设置代理
_locationManager.delegate =self;
定位精度
[_locationManagersetDesiredAccuracy:kCLLocationAccuracyBest];
请求用户权限:分为:?只在前台开启定位?在后台也可定位,
//注意:建议只请求?和?中的一个,如果两个权限都需要,只请求?即可,
//??这样的顺序,将导致bug:第一次启动程序后,系统将只请求?的权限,?的权限系统不会请求,只会在下一次启动应用时请求?
if ([[[UIDevicecurrentDevice] systemVersion]floatValue] >= 8) {
//[_locationManager requestWhenInUseAuthorization];//?只在前台开启定位
[_locationManagerrequestAlwaysAuthorization];//?在后台也可定位
}
iOS9新特性:将允许出现这种场景:同一app中多个location manager:一些只能在前台定位,另一些可在后台定位(并可随时禁止其后台定位)。
if ([[[UIDevicecurrentDevice] systemVersion]floatValue] >= 9) {
_locationManager.allowsBackgroundLocationUpdates =YES;
}
更新用户位置
[_locationManagerstartUpdatingLocation];
5、InfoPlist 加字段
<key>UIBackgroundModes</key>
<string>location</string>
<key>NSLocationAlwaysUsageDescription</key>
<string></string>
6、定位代理经纬度回调
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *newLocation = locations[0];
CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
NSLog(@"旧的经度:%f,旧的纬度:%f",oldCoordinate.longitude,oldCoordinate.latitude);
[manager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoderalloc]init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError *_Nullable error) {
for (CLPlacemark *placein placemarks) {
NSLog(@"name,%@",place.name); // 位置名
NSLog(@"thoroughfare,%@",place.thoroughfare); // 街道
NSLog(@"subThoroughfare,%@",place.subThoroughfare);// 子街道
NSLog(@"locality,%@",place.locality); // 市
NSLog(@"subLocality,%@",place.subLocality); // 区
NSLog(@"country,%@",place.country); // 国家
id selectedLocationName = [[NSUserDefaultsstandardUserDefaults] objectForKey:UDK_SELECTED_LOCATION];
if(selectedLocationName ==nil)
{
[[NSUserDefaultsstandardUserDefaults] setObject:place.localityforKey:UDK_SELECTED_LOCATION];
[[NSUserDefaultsstandardUserDefaults] synchronize];
}
}
}];
}