簡體   English   中英

如何獲取定位服務的准確授權狀態?

[英]How to get the exact authorization status of location service?

如果用戶明確拒絕了此應用程序的授權,或者在設置中禁用了定位服務,它將返回拒絕狀態。 我怎么知道它的確切原因?

我已經做了這兩個功能來檢查每個案例


如果用戶明確拒絕您的應用授權,您可以像這樣檢查,

+ (BOOL) isLocationDisableForMyAppOnly
{
    if([CLLocationManager locationServicesEnabled] &&
       [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
    {
        return YES;
    }

    return NO;
}

如果在“設置”中禁用了位置服務,

+ (BOOL) userLocationAvailable {
    return [CLLocationManager locationServicesEnabled];
}

而我正在使用它,

if([UserLocation userLocationAvailable]) {
    //.... Get location.
}
else
{
    if([UserLocation isLocationDisableForMyAppOnly]) {
        //... Location not available. Denied accessing location.
    }
    else{
        //... Location not available. Enable location services from settings.
    }
}

PS UserLocation是一個獲取用戶位置的自定義類。

迅速:

我已經做了這兩個功能來檢查每個案例

如果用戶明確拒絕您的應用授權,您可以像這樣檢查,

class func isLocationDisableForMyAppOnly() -> Bool {
    if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == .denied {
        return true
    }
    return false
}

如果在“設置”中禁用了位置服務,

class func userLocationAvailable() -> Bool {
    return CLLocationManager.locationServicesEnabled()
}

而我正在使用它,

if UserLocation.userLocationAvailable() {
        //.... Get location.
} else {
    if UserLocation.isLocationDisableForMyAppOnly() {
        //... Location not available. Denied accessing location.
    } else {
        //... Location not available. Enable location services from settings.
    }
}

PS UserLocation是一個獲取用戶位置的自定義類。

迅速

使用:

CLLocationManager.authorizationStatus()

獲取授權狀態。 這是一個CLAuthorizationStatus ,你可以像這樣打開不同的狀態:

let status = CLLocationManager.authorizationStatus()
switch status {
    case .authorizedAlways:
        <#code#>
    case .authorizedWhenInUse:
        <#code#>
    case .denied:
        <#code#>
    case .notDetermined:
        <#code#>
    case .restricted:
        <#code#>
}

斯威夫特 5.0 iOS 14.0

由於'authorizationStatus()' was deprecated in iOS 14.0您應該直接使用該實例。

authorizationStatus現在是CLLocationManager一個屬性。

您可以使用以下示例:

import CoreLocation

class LocationManager {
    private let locationManager = CLLocationManager()
    
    var locationStatus: CLAuthorizationStatus {
        locationManager.authorizationStatus
    }
}

也看看這個問題: CLLocationManager 的 AuthorizationStatus is deprecated on iOS 14

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM