我已经实现了一个位置授权回调函数并且它可以工作,但是查看代码我似乎已经获得了触发函数但从未真正按预期使用该函数。请您评论一下我有多糟糕,以及是否可以接受我所做的事情。
import UIKit
import CoreLocation
class ViewController___Main_menu: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
print("services are enabled")
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
print("Not determined")
case .restricted:
print("Resticted")
case .denied:
print("Denied")
case .authorizedAlways, .authorizedWhenInUse:
print("Access")
@unknown default:
print("unknown error")
}
} else {
print("not enabled")
}
}
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus){
print("Status: \(status)")
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
print("Not determined")
case .restricted:
print("Resticted")
case .denied:
print("Denied")
case .authorizedAlways, .authorizedWhenInUse:
print("Access")
@unknown default:
print("unknown error")
}
}
}
最佳答案
看起来您正在请求访问位置服务,然后立即检查授权状态,希望它立即可用。这不是它的工作方式。当您使用 locationManager.requestWhenInUseAuthorization
请求位置时,请求会异步发生。
当位置状态发生变化时,它将调用包含新状态的 locationManager(_:didChangeAuthorization)
函数。当用户在出现的提示上点击“允许”或“拒绝”时,就会发生这种情况。当他们进入设置并在那里更改权限时也会发生这种情况
所以为了更清楚,在请求位置之前检查并记录授权状态。使用以下方法可以知道位置请求是成功还是失败:
func locationManager(CLLocationManager, didUpdateLocations: [CLLocation])
func locationManager(CLLocationManager, didFailWithError: 错误)
您将使用 CLLocationManager.locationServicesEnabled()
检查来包装对位置服务的请求。如果设备的位置关闭,则请求位置只会导致错误。
关于ios - 这是对位置授权回调的可接受使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55703725/