從 iOS 16/Xcode 14 開始,我收到此錯誤:
如果在主執行緒上呼叫此方法,可能會導致 UI 無回應。相反,請考慮等待 -locationManagerDidChangeAuthorization: 回呼并首先檢??查授權狀態。”?
我正在觀察滾動凍結和長按凍結。
蘋果建議的應該怎么做?
這是我當前的代碼段
/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
}
我按照這里的建議嘗試了 async/await,但它沒有解決問題。https://developer.apple.com/forums/thread/714467
uj5u.com熱心網友回復:
LocationManager 的authorizationStatus目的是在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://www.uj5u.com/shujuku/521838.html
