如何检查用户是否在NSLocationAlwaysAndWhenInUseUsageDescription Swift 3.2上单击否

时间:2017-11-04 04:55:31

标签: ios swift ios-permissions

当用户在MainViewController

override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
}

viewDidLoad()将会运行并显示警告

enter image description here

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
        <string>Accessing user location to determine the nearest pickup location</string>
        <key>NSLocationWhenInUseUsageDescription</key>
        <string>Accessing user location to determine the nearest pickup location</string>

主要问题是,如果用户点击“不允许”,我该如何检查?例如

// Example code snippet, not from apple officials
if NSlocation is nil then I want to do some alert

2 个答案:

答案 0 :(得分:2)

如果用户选择拒绝您的应用访问位置服务,则CLLocationManager.authorizationStatus()将为.denied(但您也应注意.restricted。如果您希望收到通知当用户选择是否允许或拒绝您的应用时,您可以自己做位置管理员delegate并实施正确的方法:

class MainViewController: CLLocationManagerDelegate{

    let locationManager = CLLocationManager()

    override func viewDidLoad() -> Void{
        super.viewDidLoad()
        locationManager.delegate = self
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) -> Void{
        switch status{
            case .authorizedAlways, .authorizedWhenInUse:
                // You're allowed to use location services
            case .denied, .restricted:
                // You can't use location services
            default:
                // This case shouldn't be hit, but is necessary to prevent a compiler error
        }
    }
}

答案 1 :(得分:0)

使用CLLocationManager下面的委托方法检查用户在权限提醒中点击不允许按钮。

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .denied:
           print("Show you own alert here")
            break
        }
    }

要在位置设置中重定向用户,请按照以下步骤操作:

  1. 添加网址类型“prefs”,如下图所示 enter image description here

  2. 在按钮操作上编写此代码:

    UIApplication.sharedApplication().openURL(NSURL(string:"prefs:root=LOCATION_SERVICES")!)