正在尝试在 iOS Swift 中获取位置权限

Trying to get location permission in iOS Swift

我正在开发一个按钮,如果他授予应用程序位置权限,该按钮会将用户发送到地图应用程序。问题是,如果我单击该按钮一次并拒绝位置许可,则下次我单击该按钮时,该应用程序不会再次请求许可。好像用户有 "only one shot at granting maps permission"。

下面是我用来以编程方式创建带有回调函数的按钮的代码。还有 "Custom iOS Target Properties" 的屏幕截图,其中我包含了隐私 - 位置使用说明以便能够使用用户位置。

directionsButton.addTarget(self, action: #selector(getDirection), for:   UIControlEvents.touchUpInside)


func getDirection(sender: UIButton!) {
    print("1")
    if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
        CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
       let url = URL(string: "http://maps.apple.com/?daddr=60.79281049999999,10.688968899999963")
       if (UIApplication.shared.canOpenURL(url!)) {
            UIApplication.shared.openURL(url!)
        } else {
            print("Error")
        }
        print("2")
    } else{
        LocationManager.requestWhenInUseAuthorization()
        print("3")
    }
    print("4")
}

/*
 - Callback function for changes in location permissions
 */
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus){
    print("change in auth")
    if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse){
        let url = URL(string: "http://maps.apple.com/?daddr=60.79281049999999,10.688968899999963")
        if (UIApplication.shared.canOpenURL(url!)) {
            UIApplication.shared.openURL(url!)
        } else {
            print("Error")
        }
    } else{
        self.view.makeToast("Couldn't get location permission", duration: 3.0, position: .bottom)
    }
}

Picture of permissions added in the info-file

Seems like the user have "only one shot at granting maps permission".

是的,位置权限就是这种情况,地址簿访问权限等其他事情也是如此。 您的应用程序可以检测到用户之前拒绝了权限,如果是,则告诉他们需要通过设置使用名为 "Take me to settings" 或其他名称的按钮来启用它。 单击按钮后,您可以通过以下方式启动应用程序设置:

 UIApplication.shared.open(appSettings as URL, options: [:], completionHandler: { (results) in
    ...
     })