您的位置:首页 > 移动开发 > IOS开发

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

2015-10-06 10:21 585 查看
地图定位请求位置信息在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


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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息