前言:
項目開發(fā)中經(jīng)常會有獲取用戶位置的需求豪嗽,如天氣、生活圈张遭、附近的人等
實現(xiàn):
1瞬项、創(chuàng)建一個NSObject類導(dǎo)入?#import <CoreLocation/CoreLocation.h>
2.在info.plist中加入權(quán)限
NSLocationAlwaysUsageDescription (始終,在iOS8-10中使用朋沮,iOS11已 ?Deprecated蛇券,官網(wǎng)解析:A message that tells the user why the app is requesting access to the user's location at all times.)
NSLocationWhenInUseUsageDescription(使用應(yīng)用期間,官網(wǎng)解析:A message that tells the user why the app is requesting access to the user’s location information while the app is running in the foreground.)
NSLocationAlwaysAndWhenInUseUsageDescription(iOS11新增始終獲取位置信息 官網(wǎng)解析:A message that tells the user why the app is requesting access to the user’s location information at all times.)
3.在頭文件定義location管理類和協(xié)議
@interface JCLocation () <CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locManager;
@property (nonatomic, strong) CLGeocoder *coder; // 反地理編碼位置
@end
4.初始化
self.locManager = [[CLLocationManager alloc]init];
self.coder? ? ? = [[CLGeocoder alloc]init];
if (@available(iOS 8.0, *)) { ? //ios 8需要申請權(quán)限
? ? ? [self.locManager requestAlwaysAuthorization]; ? ? ? ?
? ? ? [self.locManager requestWhenInUseAuthorization];
}
if (@available(iOS 9.0, *)) { ? ?//iOS9后允許后臺刷新
? ??????if ([self.locManager respondsToSelector:@selector(allowsBackgroundLocationUpdates)]) {
? ? ? ? ??self.locManager.allowsBackgroundLocationUpdates = YES;
}
}
self.locManager.delegate = self;
self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locManager.pausesLocationUpdatesAutomatically = NO; //是否允許自動暫停更新位置默認yes
[self.locManager startUpdatingLocation]; //開始更新位置
5.位置更新后delegate回調(diào)
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
? ??if (locations.count > 0) {
? ??????CLLocation *loc = [locations lastObject];
? ? ? ??NSLog(@"lat = %f, long = %f",loc.coordinate.latitude,loc.coordinate.longitude); //至此如果成功就可以打印經(jīng)緯度信息了
? ? ?//以下為反地理編碼位置方法樊拓,有時候會出現(xiàn)偏差過大纠亚,代碼中包含WGS84矯正? ? ? ??
? ? ? ??[_coder reverseGeocodeLocation:location ? ?completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
? ??????CLPlacemark *pmark = [placemarks firstObject];
? ? ? ? //CLPlacemark類中包含了國家、地區(qū)筋夏,城市蒂胞,街道等詳細信息
}];
? ?}
}
6.定位失敗delegate回調(diào)
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{ ?
? ??????switch ([error code]) {
? ??????????case kCLErrorNetwork:
? ??????????????????DLog(@"no network...");
? ??????????????break;
? ??????????case kCLErrorDenied:
? ??????????????????DLog(@"Access to location or ranging has been denied by the user");
? ??????????????break;
? ??????????default:
? ??????????????break;
? ? ? ?}
}?
7.停止定位
[self.locManager stopUpdatingLocation];
8.注意
[self.locManager startUpdatingLocation] 不要寫成了?[self.locManager startUpdatingHeading];
startUpdatingHeading是更新指南針方向的
本文參考Demo