定位权限授权 - iOS

关于介入地图相关功能后会遇到类似定位的子功能,由此引来了此定位权限授权相关.


效果图

首先,需要导入 CoreLocation 的框架并创建管理对象从而实现后续的相关操作;

#import <CoreLocation/CoreLocation.h>

其中里面会包含一些参数属性方法等,例如:
1)是否开启位置服务

/*
 *  locationServicesEnabled
 *
 *  Discussion:
 *      Determines whether the user has location services enabled.
 *      If NO, and you proceed to call other CoreLocation API, user will be prompted with the warning
 *      dialog. You may want to check this property and use location services only when explicitly requested by the user.
 */
+ (BOOL)locationServicesEnabled API_AVAILABLE(ios(4.0), macos(10.7));

2)设置定位所期望的精准度,其中会有响应的枚举值可供选择,但精准度越高所消耗的设备电源性能也会随之受其影响,例如:导航模式

/*
 *  desiredAccuracy
 *  
 *  Discussion:
 *      The desired location accuracy. The location service will try its best to achieve
 *      your desired accuracy. However, it is not guaranteed. To optimize
 *      power performance, be sure to specify an appropriate accuracy for your usage scenario (eg,
 *      use a large accuracy value when only a coarse location is needed). Use kCLLocationAccuracyBest to
 *      achieve the best possible accuracy. Use kCLLocationAccuracyBestForNavigation for navigation.
 *      The default value varies by platform.
 */
@property(assign, nonatomic) CLLocationAccuracy desiredAccuracy;

精准度 desiredAccuracy 所对应的枚举值相关:
/*
 *  kCLLocationAccuracy<x>
 *  
 *  Discussion:
 *    Used to specify the accuracy level desired. The location service will try its best to achieve
 *    your desired accuracy. However, it is not guaranteed. To optimize
 *    power performance, be sure to specify an appropriate accuracy for your usage scenario (eg,
 *    use a large accuracy value when only a coarse location is needed).
 */
extern const CLLocationAccuracy kCLLocationAccuracyBestForNavigation API_AVAILABLE(ios(4.0), macos(10.7));// 最近
extern const CLLocationAccuracy kCLLocationAccuracyBest;// 最优
extern const CLLocationAccuracy kCLLocationAccuracyNearestTenMeters;// 十米
extern const CLLocationAccuracy kCLLocationAccuracyHundredMeters;// 百米
extern const CLLocationAccuracy kCLLocationAccuracyKilometer;// 千米
extern const CLLocationAccuracy kCLLocationAccuracyThreeKilometers;// 三千米

3)设置定位距离过滤的参数,若此次与上次定位所产生的距离差值大于或等于此设定值时则会调用代理方法

/*
 *  distanceFilter
 *  
 *  Discussion:
 *      Specifies the minimum update distance in meters. Client will not be notified of movements of less 
 *      than the stated value, unless the accuracy has improved. Pass in kCLDistanceFilterNone to be 
 *      notified of all movements. By default, kCLDistanceFilterNone is used.
 */
@property(assign, nonatomic) CLLocationDistance distanceFilter;

4)开始 & 停止位置的更新

/*
 *  startUpdatingLocation
 *  
 *  Discussion:
 *      Start updating locations.
 */
- (void)startUpdatingLocation API_AVAILABLE(watchos(3.0)) API_UNAVAILABLE(tvos);

/*
 *  stopUpdatingLocation
 *  
 *  Discussion:
 *      Stop updating locations.
 */
- (void)stopUpdatingLocation;

5)设置代理(delegate)后的一些常用代理方法

locationManager.delegate = self;

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    NSLog(@"获取定位信息 --- 成功");
}

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

其次,声明全局的变量 CLLocationManager,此处需要注意若使用局部变量的方式会调用授权方法失败;

/** 位置管理*/
CLLocationManager *locationManager;

再其次,初始化设置代理并配置系统位置权限授权操作相关
注:此处需要判断一下系统的版本号,避免异常闪退,因属性是在系统8.0基础之上才可以使用

#pragma mark - ****************************** 获取位置验证权限
/**
 获取位置验证权限(作用域: 地图 & 定位相关)

 @param vc 当前视图控件
 */
- (void)YHGetLocationPermissionVerifcationWithController:(UIViewController *)vc {
    BOOL enable = [CLLocationManager locationServicesEnabled];
    NSInteger state = [CLLocationManager authorizationStatus];
    
    if (!enable || 2 > state) {// 尚未授权位置权限
        if (8 <= [[UIDevice currentDevice].systemVersion floatValue]) {
            NSLog(@"系统位置权限授权弹窗");
            // 系统位置权限授权弹窗
            locationManager = [[CLLocationManager alloc] init];
            locationManager.delegate = self;
            [locationManager requestAlwaysAuthorization];
            [locationManager requestWhenInUseAuthorization];
        }
    }
    else {
        if (state == kCLAuthorizationStatusDenied) {// 授权位置权限被拒绝
            UIAlertController *alertCon = [UIAlertController alertControllerWithTitle:@"提示"
                                                                              message:@"访问位置权限暂未授权"
                                                                       preferredStyle:UIAlertControllerStyleAlert];
            [alertCon addAction:[UIAlertAction actionWithTitle:@"暂不设置" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            
            [alertCon addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                dispatch_after(0.2, dispatch_get_main_queue(), ^{
                    NSURL *url = [[NSURL alloc] initWithString:UIApplicationOpenSettingsURLString];// 跳转至系统定位
                    if( [[UIApplication sharedApplication] canOpenURL:url]) {
                        [[UIApplication sharedApplication] openURL:url];
                    }
                });
            }]];
            
            [vc presentViewController:alertCon animated:YES completion:^{
                
            }];
        }
    }
}

GitHub: https://github.com/survivorsfyh/YHTools/tree/master/YHAccessAuthorization


以上便是此次内容小结,项目中用到的功能不多没有深挖,还有很多可拓展的地方,有什么不足还望多多指点!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 几个月前我在微信上接触到玛雅历法,并且跟着一个专门传播这个历法的团队免费学习了一阵子,刚开始的时候,我觉得很新鲜很...
    牧羊宇歌阅读 2,920评论 0 0
  • 最近在做小程序博客内容的管理,因为使用了第三方的云数据库,所以在做列表分页的时候不能使用Laravel自带的分页类...
    曼巴童鞋阅读 4,359评论 0 1
  • 前期的镇痛 后面到了医院,疼痛更加密集,上午在人民医院检查了很多。感觉要生,坐了两个小时左右到了市立医院,一点左右...
    负面絮叨叨阅读 1,328评论 0 1
  • 今天去上班的路上看到一只被车撞死的猫咪,心情不是怎么好。天知道,我最喜欢小猫了。什么样的猫咪,都是我心中最美好的事...
    平澜阅读 2,682评论 1 1
  • 连接 题意:问最少要跳跃几次两只青蛙才能见面.思路:根据题意,两个青蛙跳到同一个点上才算是遇到了,所以有 (x+m...
    Anxdada阅读 3,818评论 0 0

友情链接更多精彩内容