【问题标题】:How to check location authorization status at the click of a button in iOS 14?如何在 iOS 14 中单击按钮检查位置授权状态?
【发布时间】:2021-02-12 12:25:46
【问题描述】:

如何使用 Core Location 的 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
        }
        ...

【问题讨论】:

  • locationManagerDidChangeAuthorization中的操作方式相同
  • @pronebird 你能澄清一下“同样的方式”是什么意思吗?

标签: swift core-location cllocationmanager ios14


【解决方案1】:

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

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

  • 隐私 - 位置始终和使用时使用说明
  • 隐私 - 使用时的位置使用说明

【讨论】:

  • 是的,我也添加了隐私使用说明,但是在模拟器中弹出它没有运气。我注意到,当我在上面的编辑中使用已弃用的 authorizationStatus() 类方法而不是 locationManagerDidChangeAuthorization 委托方法时,我可以得到这个弹出窗口。
  • 我已经复制了你的代码,创建了一个新的 VC,带有一个调用 getLocation() 的按钮,并且在我的 plist 文件中使用了两个用法描述,模拟器会询问位置。你在真机上试过吗?
  • 我在 iPhone 的 iOS 14.1 上运行 XCode 12.2 测试版文件时遇到问题,因此无法在真实设备上进行测试。但是我能够降级到 XCode 12,并且代码最终可以在我的 iPhone 上运行。感谢您的帮助@perage,谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多