-引入头文件
#import <CoreLocation/CoreLocation.h>
-声明变量
@property (nonatomic, strong)CLLocationManager *locationManager;
-实现代理方法
@interface LocationTool : NSObject <CLLocationManagerDelegate>
-初始化locationManager
- (instancetype)init
{
self = [super init];
if (self) {
_locationManager = [[CLLocationManager alloc]init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = kCLDistanceFilterNone;
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
[_locationManager requestWhenInUseAuthorization];
}
}
return self;
}
-实现代理方法
#pragma mark CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(@"定位出错");
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
NSLog(@"定位成功");
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
switch (status) {
case kCLAuthorizationStatusNotDetermined: //用户还没有被请求获取授权
if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[_locationManager requestWhenInUseAuthorization];
}
NSLog(@"kCLAuthorizationStatusNotDetermined");
break;
default:
break;
}
}
-支持iOS8
添加:NSLocationWhenInUseUsageDescription, NSLocationAlwaysUsageDescription
代码下载:CLLocationManager