用户拒绝位置服务后再次请求权限?

Tru*_*an1 26 iphone core-location ios swift ios8

我跟踪用户的位置,并在我的负载首次加载时请求权限:

locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
Run Code Online (Sandbox Code Playgroud)

如果用户拒绝,但后来通过启用我的应用程序中的配置选项改变了主意,我该如何再次询问?例如,我有一个自动检测用户位置的开关,所以当他们启用它时,我试图这样做:

@IBAction func gpsChanged(sender: UISwitch) {
    // Request permission for auto geolocation if applicable
    if sender.on {
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码似乎没有做任何事情.我希望它会再次询问用户是否允许该应用程序跟踪用户的位置.这可能吗?

bgi*_*ham 56

操作系统只会提示用户一次.如果他们拒绝允许,就是这样.你可以做的是直接用户设置为你的应用程序通过传递UIApplicationOpenSettingsURLStringUIApplicationopenURL:方法.从那里,他们可以根据需要重新启用位置服务.也就是说,你可能不应该过于咄咄逼人地批评它们以获得许可.


All*_*len 14

权限弹出窗口仅显示一次.因此,我们必须在此之后将用户重定向到"设置".这里是Swift中的代码:

 import CoreLocation 
 @IBAction func userDidClickButton(_ sender: Any) {

    // initialise a pop up for using later
    let alertController = UIAlertController(title: "TITLE", message: "Please go to Settings and turn on the permissions", preferredStyle: .alert)
    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }
        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in })
         }
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)
    alertController.addAction(settingsAction)

    // check the permission status
    switch(CLLocationManager.authorizationStatus()) {
        case .authorizedAlways, .authorizedWhenInUse:
            print("Authorize.")
            // get the user location
        case .notDetermined, .restricted, .denied:
            // redirect the users to settings
            self.present(alertController, animated: true, completion: nil)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 快速说明:如果 case 是 `.notDetermined`,那么我们可以使用 CLLocationManager.requestForWhenInUseAuthorization() 函数(因为它只能使用一次,而 `.notDetermined` 意味着用户尚未决定位置权限)您的应用程序)。 (3认同)