【发布时间】:2017-03-18 00:47:13
【问题描述】:
是否每次应用首次运行时都会调用 locationManager(_:didChangeAuthorization:),即使未调用位置管理器方法 requestWhenInUseAuthorization() 或 startUpdatingLocation()?我正在尝试通过单击我在下面的@IBAction 中调用的按钮来报告位置:
@IBAction func findOutPressed(_ sender: UIButton) {
getLocation()
}
我的 CoreLocation 代码在下面的扩展中:
extension ViewController: CLLocationManagerDelegate {
// Called from findOutPressed to get location when button is clicked
func getLocation() {
let status = CLLocationManager.authorizationStatus()
handleLocationAuthorizationStatus(status: status)
}
// Respond to the result of the location manager authorization status
func handleLocationAuthorizationStatus(status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .authorizedWhenInUse, .authorizedAlways:
locationManager.startUpdatingLocation()
case .denied:
print("I'm sorry - I can't show location. User has not authorized it")
case .restricted:
print("Access denied - likely parental controls are restricting use in this app.")
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
handleLocationAuthorizationStatus(status: status)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let currentLocation = locations.last
let labelText = "My location is: latitude = \((currentLocation?.coordinate.latitude)!), longitude = \((currentLocation?.coordinate.longitude)!)"
resultLabel.text = labelText
locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Dang, there was an error! Error: \(error)")
}
}
我发现 locationManager(didChangeAuthorization:) 正在立即执行,即使 @IBAction findOutPressed 没有被点击触发,并且结果正在我最初的空白中更新用户单击按钮之前的结果标签。我知道我可以设置一个标志来确定是否单击了按钮,从而防止标签过早更新,但我试图了解何时触发 locationManager(_:didChangeAuthorization)。苹果 说: “只要应用程序使用位置服务的能力发生变化,就会调用此方法。可能会发生变化,因为用户允许或拒绝为您的应用程序或整个系统使用位置服务。” 这似乎没有涵盖应用程序首次运行时触发的情况。我很感谢任何可以让我直接了解授权更改发生情况的人。抱歉,如果我错过了一些基本的东西。 谢谢!
【问题讨论】:
标签: ios swift core-location cllocationmanager uiapplicationdelegate