請求使用位置服務的許可權

檢查應用程式的授權狀態:

//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 文件