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

48

我使用以下代码跟踪用户位置,并在我的加载时首次请求权限:

```javascript navigator.geolocation.getCurrentPosition(success, error); ```
```success```和```error```是回调函数。
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()

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

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

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

6个回答

83

操作系统只会提示用户一次。如果他们拒绝了权限,那就是这样了。你可以做的是通过将 UIApplicationOpenSettingsURLString 传递给 UIApplicationopenURL: 方法,将用户引导到您应用程序的设置界面。从那里,他们可以重新启用位置服务(如果他们愿意的话)。尽管如此,你可能不应该过于强调向他们请求权限。


41

权限弹出窗口仅显示一次。 因此,之后我们必须将用户重定向到设置。 这是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)
    }
}

3
简要说明:如果case.notDetermined,则可以使用 CLLocationManager.requestForWhenInUseAuthorization()函数(因为它只能使用一次,而.notDetermined表示用户尚未决定是否允许您的应用程序使用位置权限)。 - HirdayGupta

3

您可以有另一种解决方案!! 您可以显示自己的警报,其中包含更好的消息,可以说服用户允许接收您的应用程序的推送通知。如果用户允许,则只向其显示默认权限警报以启用推送通知,否则如果用户不允许,则不要显示默认警报。实际上,您可以将相应标志保存在数据库或NSUserDefaults中,并且可以在应用程序中的某些事件中再次询问用户。


这个解决方案不错,但是你强制用户点击两次才能同意,首先是你的弹出窗口,然后是苹果的。通常你会在应用程序开始时询问权限,也许在第一次启动时,也许你有一个欢迎介绍或教程,这会增加一个额外的步骤。通常情况下,苹果更喜欢最多保留1或2个步骤。 - MajinDageta

2

你只有一次机会。如果用户拒绝了权限,他们必须通过设置应用程序来启用它们。请参见在CLLocationManager中请求使用位置服务的权限。


1

@TruMan1 请再检查一下,我已经上传了带有联系人权限的代码。 - CrazyPro007
你能描述一下它是如何工作的吗? - anon

0

对于 Health Kit API,开发者可以将另一个权限添加到 readTypes Set<HKObjectType> 中,用户将被重新提示允许权限。我不确定位置服务是否以同样的方式工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接