iOS经典讲解之地图定位请求位置信息时出现的问题

地图定位请求位置信息在iOS8之后新增两个方法:

- (void)requestWhenInUseAuthorization

- (void)requestAlwaysAuthorization,

但是在使用这两个方法的时候需要手动在Info.plist文件加两个字段,

NSLocationWhenInUseUsageDescription

NSLocationAlwaysUsageDescription

这两个字段没什么特别的意思,就是自定义提示用户授权使用地理定位功能时的提示语。

系统给出了说明:

/* If the NSLocationWhenInUseUsageDescription key is not specified in your
 *      Info.plist, this method will do nothing, as your app will be assumed not
 *      to support WhenInUse authorization.
 */

- (void)requestWhenInUseAuthorization __OSX_AVAILABLE_STARTING(__MAC_NA, __IPHONE_8_0);


/*      If the NSLocationAlwaysUsageDescription key is not specified in your
 *      Info.plist, this method will do nothing, as your app will be assumed not
 *      to support Always authorization.
 */

- (void)requestAlwaysAuthorization __OSX_AVAILABLE_STARTING(__MAC_NA, __IPHONE_8_0);

示例图片如下:

这样添加代码就可以了:

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化
    self.locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    self.locationManager.delegate = self;
    // 定位精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置多少米更新一次距离
    self.locationManager.distanceFilter = 100;
    // 什么时候请求位置信息 注意:  If the NSLocationAlwaysUsageDescription key is not specified in your Info.plist, this method will do nothing, as your app will be assumed not to support Always authorization. 需要设置plist文件添加NSLocationAlwaysUsageDescription为key即可
    
    [self.locationManager requestAlwaysAuthorization];
    // 开始请求位置信息
    [self.locationManager startUpdatingLocation];
    
}
#pragma mark -- 代理方法
//定位成功时代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations firstObject];
  NSLog(@"%@", location);
   
}
// 定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    // 错误信息描述
    NSLog(@"%@", [error localizedDescription]);
}
@end

接下来就可以获取位置信息了,出现如下提示,说明请求成功了:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值