由于iOS 16/Xcode 14,我得到了以下错误:
如果在主线程上调用此方法,则会导致UI无响应。相反,考虑等待-locationManagerDidChangeAuthorization:回调并首先检查authorizationStatus“?
我正在观察滚动冻结和长时间的压力冻结。
苹果的建议应该怎么做呢?
这是我当前的代码段
/In ViewDidLoad
if CLLocationManager.locationServicesEnabled() {
let authorizationStatus: CLAuthorizationStatus
if #available(iOS 14, *) {
authorizationStatus = locationManager.authorizationStatus
} else {
authorizationStatus = CLLocationManager.authorizationStatus()
}
switch authorizationStatus {
case .authorizedAlways, .authorizedWhenInUse:
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.startUpdatingLocation()
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.allowsBackgroundLocationUpdates = true
//////here data loading happens too////////////
case .notDetermined:
case .restricted:
case .denied:
@unknown default:
print("Location services are not enabled")
}
/outside ViewDidLoad
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
///location database related stuff
}
我尝试了这里建议的异步/等待,但是它没有解决这个问题。https://developer.apple.com/forums/thread/714467
发布于 2022-10-20 15:14:08
当authorizationStatus
委托指示您的应用程序授权使用位置服务时,就会使用LocationManager的CLLocationManager
。
当应用程序的授权状态发生变化时,系统调用CLLocationManager
委托方法locationManagerDidChangeAuthorization(_ :)
。这可以用于用户发起的更改,也可以是当用户在请求requestWhenInUseAuthorization()
或requestAlwaysAuthorization()
后更改权限时。每当您创建一个新的CLLocationManager
实例时,它也将调用委托方法,因此它将提示您在第一次运行时检查该值。
当调用委托方法时,您应该从authorizationStatus
属性中获取值并存储它。如果状态随后被更改(手动或响应系统使用提示),它将再次被调用,您应该更新存储的值;如果没有,则保存的值仍然有效,并且不需要从viewDidLoad
请求它。
编辑以地址注释..。
您不应该在viewDidLoad
中运行位置代码--当您获得更新的位置时,应该从委托开始运行该代码。在viewDidLoad中启动位置服务,例如。通过这样的称呼:
//struct/class-level properties
var locationManager: CLLocationManager
var authStatus = CLAuthorizationStatus.notDetermined
func startLocationServices() {
locationManager = CLLocationManager()
locationManager.delegate = self
if authStatus == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
locationManager.startUpdatingLocation()
}
然后,使用CLLocationManagerDelegate
提供动作位置信息。
extension HomeVC: CLLocationManagerDelegate {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
authStatus = manager.authorizationStatus
// you could use a `didSet` on `authStatus` to react to changes
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let newLocation = locations.first {
process(newLocation)
}
}
}
然后在process(_:)
里做你在viewDidLoad
里想做的事
https://stackoverflow.com/questions/74141609
复制相似问题