如何在授予位置权限后执行任务 ios

How to execute a task after location permission granted ios

我正在尝试设置一个登录页面,要求用户提供一些权限,包括:位置、通知和相机。我设置了 3 个不同的视图控制器,每个都要求获得其中一个权限并解释原因。在每个视图控制器上,我在底部都有一个按钮,上面写着 "Grant Permission"。

当用户单击按钮时,我希望弹出权限对话框,一旦用户单击允许,我想转换到下一个视图控制器。

这是我现在拥有的:

class OnboardingStep2:UIViewController{

    override func viewDidLoad() {
        self.view.backgroundColor = StyleKit.orangeWhite()
    }

    @IBAction func getPermission(sender: AnyObject) {

        dispatch_sync(dispatch_get_main_queue()) {
            let locManager = CLLocationManager()
            locManager.requestAlwaysAuthorization()

        }

        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized) {
            self.performSegueWithIdentifier("goToStep3", sender: self)
        }

    }
}

我试过使用 dispatch 来排队任务,但是当使用 async 时,弹出权限对话框然后立即关闭,因为授权检查是 运行(我假设)。使用 dispatch_sync,永远不会显示对话。

执行此操作的最佳方法是什么,我希望首先弹出权限对话框,一旦用户单击“允许”,我就想继续。

符合CLLocationManagerDelegate

然后这样调用:

Swift 3.0

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch status {
    case .notDetermined:
        manager.requestLocation()
    case .authorizedAlways, .authorizedWhenInUse:
        // Do your thing here
    default:
        // Permission denied, do something else
    }
}

Swift 2.2

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    switch status {
    case .NotDetermined:
        manager.requestLocation()
    case .AuthorizedAlways, .AuthorizedWhenInUse:
        // Do your thing here
    default:
        // Permission denied, do something else
    }
}

Swift 5

实施CLLocationManagerDelegate 这个函数:

func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
    switch CLLocationManager.authorizationStatus() {
    case .notDetermined:
        // User has not yet made a choice
    case .denied:
        // User has explicitly denied authorization
    case .restricted:
        // This application is not authorized to use location services.
    case .authorized, .authorizedAlways, .authorizedWhenInUse:
        // User has granted authorization
    default:
        // Other
    }
}