请求使用位置服务的权限

检查应用程序的授权状态:

//Swift
let status: CLAuthorizationStatus = CLLocationManager.authorizationStatus()

//Objective-C
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

根据以下常量测试状态:

//Swift
switch status {
case .NotDetermined:
    // Do stuff
case .AuthorizedAlways:
    // Do stuff
case .AuthorizedWhenInUse:
    // Do stuff
case .Restricted:
    // Do stuff
case .Denied:
    // Do stuff
}

//Objective-C
switch (status) {
    case kCLAuthorizationStatusNotDetermined:
        
        //The user hasn't yet chosen whether your app can use location services or not.
        
        break;
        
    case kCLAuthorizationStatusAuthorizedAlways:
        
        //The user has let your app use location services all the time, even if the app is in the background.
        
        break;
        
    case kCLAuthorizationStatusAuthorizedWhenInUse:
        
        //The user has let your app use location services only when the app is in the foreground.
        
        break;
        
    case kCLAuthorizationStatusRestricted:
        
        //The user can't choose whether or not your app can use location services or not, this could be due to parental controls for example.
        
        break;
        
    case kCLAuthorizationStatusDenied:
        
        //The user has chosen to not let your app use location services.
        
        break;
        
    default:
        break;
}

应用程序正在使用中获取位置服务权限

StackOverflow 文档

最简单的方法是将位置管理器初始化为根视图控制器的属性,并将权限请求放在其 viewDidLoad 中。

这会调出要求许可的警报控制器:

//Swift
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()

//Objective-C
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];

NSLocationWhenInUseUsageDescription 键添加到 Info.plist 。该值将用于警报控制器的 message 标签。

StackOverflow 文档

始终获得位置服务许可

StackOverflow 文档

要获得使用位置服务的权限,即使应用程序未处于活动状态,请使用以下调用:

//Swift
locationManager.requestAlwaysAuthorization()

//Objective-C
[locationManager requestAlwaysAuthorization];

然后将 NSLocationAlwaysUsageDescription 键添加到 Info.plist 。同样,该值将用于警报控制器的 message 标签。

StackOverflow 文档