用到地图定位的时候,会判断系统是否允许本应用定位。而[CLLocationManager locationServicesEnabled]检测的是整个iOS系统的位置服务开关,无法检测当前应用是否被关闭 下面有两种方法解决
(1)通过+locationServicesEnabled和authorizationStatus对应的状态判断
if ([CLLocationManager locationServicesEnabled] &&
([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorize || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
//定位功能可用,开始定位
[locationManger startUpdatingLocation];
} else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
NSlog("定位功能不可用,提示用户或忽略");
}
authorizationStatus对应的状态是枚举类型
kCLAuthorizationStatusNotDetermined: 用户尚未做出决定是否启用定位服务
kCLAuthorizationStatusRestricted: 没有获得用户授权使用定位服务,可能用户没有自己禁止访问授权
kCLAuthorizationStatusDenied :用户已经明确禁止应用使用定位服务或者当前系统定位服务处于关闭状态
kCLAuthorizationStatusAuthorizedAlways: 应用获得授权可以一直使用定位服务,即使应用不在使用状态
kCLAuthorizationStatusAuthorizedWhenInUse: 使用此应用过程中允许访问定位服务
(2)通过CLLocationManagerDelegate的locationManager:didFailWithError:方法去检测
- (void)locationManager: (CLLocationManager *)manager
didFailWithError: (NSError *)error {
NSString *errorString;
[manager stopUpdatingLocation];
NSLog(@”Error: %@”,[error localizedDescription]);
switch([error code]) {
case kCLErrorDenied:
//Access denied by user
errorString = @”Access to Location Services denied by user”;
//Do something…
break;
case kCLErrorLocationUnknown:
//Probably temporary…
errorString = @”Location data unavailable”;
//Do something else…
break;
default:
errorString = @”An unknown error has occurred”;
break;
}
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Error” message:errorString delegate:self cancelButtonTitle:@”Ok” otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
具体的CLError信息可以看CLLocationManager文档