打开一个老工程,发现里面location服务用不了了,CLLocationManager的代理方法根本就不执行了,一通查找,结论如下:
第一步:在iOS8里,使用location服务,需要在Info.plist文件里添加key:
NSLocationWhenInUseUsageDescription(在使用app时,即:foreground,允许)
或者
NSLocationAlwaysUsageDescription(总是允许,包括在app退到后台),
这两个key至少添加一个,value可以为空,也可以填写自己的描述,通常都是一些,“xxx需要使用大爷您的位置,求允许”之类的。
第二步:在初始化CLLocationManager对象时,需要调用
requestWhenInUseAuthorization
或者
requestAlwaysAuthorization
设置好这两步,回调的代理方法里就能得到位置信息了。
一个完整的例子:
#import "ViewController.h"
@import CoreLocation;
@interface ViewController () <CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// ** Don't forget to add NSLocationWhenInUseUsageDescription in MyApp-Info.plist and give it a string
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
// Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
}
// Location Manager Delegate Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
NSLog(@"%@", [locations lastObject]);
}
@end