![](/img/trans.png)
[英]How to implement CLLocationManager.requestLocation() on iOS 8 or older?
[英]CLLocationManager requestLocation button is throwing errors on iOS 15 Xcode 13 Beta 2
我正在嘗試請求一次訪問該位置。 我已經對 info.plist 文件進行了必要的添加,如下所示:
現在,當我使用以下代碼調用 updateLocation 時,出現以下錯誤:
[MKCoreLocationProvider] CLLocationManager(<CLLocationManager: 0x600001cf4470>) for <MKCoreLocationProvider: 0x600002ce03f0> did fail with error: Error Domain=kCLErrorDomain Code=1 "(null)"
The operation couldn’t be completed. (kCLErrorDomain error 1.)
我也從未收到允許應用程序使用我的位置的提示。
這是 LocationManager 類的完整實現。
class LocationManager: NSObject, ObservableObject {
private let locationManager = CLLocationManager()
@Published var region = MKCoordinateRegion.defaultRegion
static let defaultDistance: CLLocationDistance = 1000000
override init() {
super.init()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.delegate = self
}
func updateLocation() {
locationManager.requestLocation()
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
DispatchQueue.main.async {
self.region = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: Self.defaultDistance, longitudinalMeters: Self.defaultDistance)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
}
我正在使用 Xcode 13 Beta 2 並在模擬器上運行。
添加請求方法:
locationManager.requestWhenInUseAuthorization()
並觀察授權狀態也添加此委托方法:
extension ViewController: CLLocationManagerDelegate {
func locationManager(_
manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .authorizedWhenInUse:
print("Authorized When in Use")
case .authorizedAlways:
print("Authorized Always")
case .denied:
print("Denied")
case .notDetermined:
print("Not determined")
case .restricted:
print("Restricted")
@unknown default:
print("Unknown status")
}
}
}
如果您在模擬器中遇到此錯誤,請確保模擬位置已激活
Target>Edit Scheme>Run>Options>Allow Location Simulation
和
Simulator>Features>Location>City Run
就我而言,我將 CLLocationButton 添加到我的子視圖控制器(也符合 CLLocationManagerDelegate)。 在此設置中,彈出窗口從未出現。
將按鈕直接添加到父視圖控制器解決了問題,彈出窗口出現。
不知道為什么,也許 CoreLocation 框架正在以某種方式搜索頂視圖控制器,但是層次結構被破壞了。 我未能在一個簡單的示例項目中復制相同的行為。 (Xcode 13 測試版 5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.