【发布时间】: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