微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在iOS 14中单击按钮来检查位置授权状态?

如何解决如何在iOS 14中单击按钮来检查位置授权状态?

我如何使用核心位置的locationManagerDidChangeAuthorization(_ :)方法来检查授权状态并按以下按钮(在@IBAction中称为)报告用户位置:

这里的问题是,当我在模拟器中运行代码时,CoreLocation不会弹出并带有警告,当按下按钮时会询问用户许可。

class CurrentLocationViewController: UIViewController,CLLocationManagerDelegate {
    
    let locationManager = CLLocationManager()
    
    // Button to check authorization status and start sending location update to the delegate
    @IBAction func getLocation() {
        locationManagerDidChangeAuthorization(locationManager)
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
    }

    // Delegate method to check authorization status and request "When In Use" authorization
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        let authStatus = manager.authorizationStatus
        if authStatus == .notDetermined {
            locationManager.requestWhenInUseAuthorization()
            return
        }
    }

编辑:在@IBAction方法中使用不赞成使用的authorizationStatus()类方法,而不是locationManagerDidChangeAuthorization(_ :)方法,可以让我在模拟器中按下按钮时弹出。我仍在试图弄清楚为什么这种修改有效,而我上面的代码却没有。

    @IBAction func getLocation() {
        let authStatus = CLLocationManager.authorizationStatus()
        if authStatus == .notDetermined {
            locationManager.requestWhenInUseAuthorization()
            return
        }
        ...

解决方法

您的代码有效-但是您还记得将隐私使用说明添加到info.plist文件吗?

将这两个条目添加到文件中,并在value字段中添加您自己的解释,然后应在模拟器中弹出它:

  • 隐私-位置始终且在使用时用法说明
  • 隐私-使用时的位置用法说明

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。