问题描述
我如何使用核心位置的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字段中添加您自己的解释,然后应在模拟器中弹出它:
- 隐私-位置始终且在使用时用法说明
- 隐私-使用时的位置用法说明