美文网首页iOSiOS知识库
iOS 实现系统方法调用定位

iOS 实现系统方法调用定位

作者: 波妞和酱豆子 | 来源:发表于2017-04-26 18:22 被阅读3496次

第一步.添加库 CoreLocation.framework

F83300D8-9BCE-41C5-A271-98A3C96D6D0E.png

第二步.在info.plist文件里添加 这两个描述 获得用户的允许权限
1.Privacy - Location When In Use Usage Description -> 是否允许此App在使用期间访问你的位置?
2.Privacy - Location Always Usage Description -> 是否允许此App永久访问你的位置?


1FE22EB2-EBCF-46C6-9E29-05FFBA20A0AB.png

第三步.开始写代码了
头文件和代理

#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>

@property (nonatomic,strong ) CLLocationManager *locationManager;//定位服务
@property (nonatomic,copy)    NSString *currentCity;//城市
@property (nonatomic,copy)    NSString *strLatitude;//经度
@property (nonatomic,copy)    NSString *strLongitude;//维度
- (void)viewDidLoad {
    [super viewDidLoad];
    [self locatemap];
    // Do any additional setup after loading the view, typically from a nib.
}
- (void)locatemap{

    if ([CLLocationManager locationServicesEnabled]) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        [_locationManager requestAlwaysAuthorization];
        _currentCity = [[NSString alloc]init];
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 5.0;
        [_locationManager startUpdatingLocation];
    }
}
#pragma mark - 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication]openURL:settingURL];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 定位成功
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    [_locationManager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //当前的经纬度
    NSLog(@"当前的经纬度 %f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    //这里的代码是为了判断didUpdateLocations调用了几次 有可能会出现多次调用 为了避免不必要的麻烦 在这里加个if判断 如果大于1.0就return
    NSTimeInterval locationAge = -[currentLocation.timestamp timeIntervalSinceNow];
    if (locationAge > 1.0){//如果调用已经一次,不再执行
        return;  
    }
    //地理反编码 可以根据坐标(经纬度)确定位置信息(街道 门牌等)
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count >0) {
            CLPlacemark *placeMark = placemarks[0];
            _currentCity = placeMark.locality;
            if (!_currentCity) {
                _currentCity = @"无法定位当前城市";
            }
            //看需求定义一个全局变量来接收赋值
            NSLog(@"当前国家 - %@",placeMark.country);//当前国家
            NSLog(@"当前城市 - %@",_currentCity);//当前城市
            NSLog(@"当前位置 - %@",placeMark.subLocality);//当前位置
            NSLog(@"当前街道 - %@",placeMark.thoroughfare);//当前街道
            NSLog(@"具体地址 - %@",placeMark.name);//具体地址
            NSString *message = [NSString stringWithFormat:@"%@,%@,%@,%@,%@",placeMark.country,_currentCity,placeMark.subLocality,placeMark.thoroughfare,placeMark.name];
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"好", nil];
            [alert show];
        }else if (error == nil && placemarks.count){
        
            NSLog(@"NO location and error return");
        }else if (error){
        
            NSLog(@"loction error:%@",error);
        }
    }];
}

希望这些工作中的节点总结能帮助到大家 谢谢

相关文章

网友评论

  • 无星灬:你好,我有几处不太明白,想请问一下。
    1.我的didUpdateLocations总是不停地在调用,所以我在想办法增加限制条件,就比如文中的locationAge进行判断,但是在第一次运行的时候,我的locationAge就已经超过1了。这导致我后面的地理位置无法运行。
    2.采用horizontalAccuracy进行判断,永远是判断>0定位成功然后反复走这个didUpdate方法,导致我其他的业务逻辑不会走。。。请问该如何解决
    _ZhangJ:static dispatch_once_t disOnce;

    dispatch_once(&disOnce,^ {});
    把判断去掉 用这个去做限制一次调用
    无星灬:@陈佳运Genius 你好,我也在探寻为什么第一次运行就超过了1,而且是200多,暂时还不知道原因
    波妞和酱豆子:你好 我刚刚看到你的回复 我想问一下 为什么你在第一次运行的时候locationAge就已经超过1了?
    这段代码的判断应该是没问题的
    NSTimeInterval locationAge = -[currentLocation.timestamp timeIntervalSinceNow];
    if (locationAge > 1.0){
    return;
    }
    如果你已经解决了 我希望能分享一下解决方法 共同学习一下 也为其他在此有困惑的同学一点帮助

本文标题:iOS 实现系统方法调用定位

本文链接:https://www.haomeiwen.com/subject/nrkwzttx.html