如果在一个App的某个部分需要用到定位功能,比如查看附近的某些信息,那么需要用到CLLocationManager这个类
导入#import <CoreLocation/CoreLocation.h>
首先创建locationManager对象
@property (nonatomic, strong) CLLocationManager *locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
[self requestLocation];
}
// 重写Getter方法
-(CLLocationManager *)locationManager{
if (!_locationManager) {
_locationManager = [[CLLocationManager alloc] init];
// 设置精度
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// 100米内不需要重新定位
_locationManager.distanceFilter = 100;
// 绑定委托
_locationManager.delegate = self;
}
return _locationManager;
}
// 请求定位
- (void) requestLocation{
// 请求用户权限 开启定位
// 判断当前App是否开启定位服务
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// 判断是否已授权
if (status == kCLAuthorizationStatusNotDetermined) {
// 请求授权
[self.locationManager requestWhenInUseAuthorization];
}
// 如果关闭定位服务 弹框提示
else if (status == kCLAuthorizationStatusDenied){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"定位服务已关闭,请在设置中找到该应用,然后开启定位服务" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alertView show];
}
else{
[self.locationManager startUpdatingLocation];
}
}
#pragma mark - CLLocationDelegate
// 授权状态改变时回调
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
if (status == kCLAuthorizationStatusDenied) {
NSLog(@"不允许");
}
else{
// 启动定位服务
[manager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// 先判断有没有位置信息
if (locations.count > 0) {
// 停止定位
[manager stopUpdatingLocation];
// 从数组中取出任意一个位置信息
CLLocation *location = [locations firstObject];
// 传入位置信息 调用数据请求方法
[self requestNearApp:location.coordinate];
}
}
nearApp.png
网友评论