作者:伤心的海2012_626 | 来源:互联网 | 2023-06-17 20:30
在ios7之前,我们进入程序提示用户开启定位是这样做的,如下: CLLocationManager*locationManager[[CLLocationM
在ios7之前,我们进入程序提示用户开启定位是这样做的,如下:
CLLocationManager * locatiOnManager= [[CLLocationManager alloc] init];//创建位置管理器
//locationManager.delegate=_instance;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=100.0f;
//定位服务是否可用
BOOL enable=[CLLocationManager locationServicesEnabled];
//是否具有定位权限
int status=[CLLocationManager authorizationStatus];
if(!enable || status<3){
//请求权限
[locationManager requestWhenInUseAuthorization];
}
但是到了ios8后,发现定位压根就不起作用,老是提示:
ios8定位解决如下:
先在info.plist定义key:(总是授权)NSLocationAlwaysUsageDescription或者使用时授权NSLocationWhenInUseUsageDescription
在.h里面
继承代码CLLocationManagerDelegate
定义CLLocationManager *_locationManager;
在.m里面定义:
- (void)startTrackingLocation {
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (status == kCLAuthorizationStatusNotDetermined) {
//总是授权
[_locationManager requestAlwaysAuthorization];
//每次授权一次
//[_locationManager requestWhenInUseAuthorization];
}
else if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways) {
[_locationManager startUpdatingLocation];
}
}
//实现代码回调
#pragma mark - CLLocationManager Delegate Methods
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
switch (status) {
case kCLAuthorizationStatusAuthorizedAlways:
case kCLAuthorizationStatusAuthorizedWhenInUse:
NSLog(@"Got authorization, start tracking location");
[self startTrackingLocation];
break;
case kCLAuthorizationStatusNotDetermined:
[_locationManager requestAlwaysAuthorization];
break;
default:
break;
}
}
调用如下:
if (IOS8) {
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
[self startTrackingLocation];
}
最后实现效果如下图,点击Allow即可定位了: