現在我只是想在螢屏上列印位置,稍后會對其進行擴展,但我得到以下控制臺輸出(應用程式也崩潰了 - 它正在物理設備上構建和運行):
2022-11-14 16:43:07.333908-0700 Countries[7257:1687502] *** Assertion failure in -[CLLocationManager requestLocation], CLLocationManager.m:1323
2022-11-14 16:43:07.334806-0700 Countries[7257:1687502] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Delegate must respond to locationManager:didUpdateLocations:'
*** First throw call stack:
(0x1c4566248 0x1bd92ba68 0x1beeea81c 0x1cfd2a654 0x1040d7308 0x1040d3ff8 0x246a377e8 0x1c69396d8 0x1c69393d8 0x1c6938d6c 0x2464f75f8 0x1c6938848 0x1c681e060 0x1c709e1d8 0x1c67e1d18 0x1c67e6674 0x1c67e5944 0x1c67e5000 0x1c682cd64 0x1c7473a30 0x1c6d3b678 0x1c737a904 0x1c7379ad0 0x1c463222c 0x1c463e614 0x1c45c251c 0x1c45d7eb8 0x1c45dd1e4 0x1fd3fd368 0x1c6a8cd88 0x1c6a8c9ec 0x1c808bce8 0x1c7fe8c24 0x1c7fd1b44 0x1040e8b20 0x1040e8bc8 0x1e2901948)
libc abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Delegate must respond to locationManager:didUpdateLocations:'
terminating with uncaught exception of type NSException
(lldb)
這是我正在使用的代碼:
import Foundation
import CoreLocation
import CoreLocationUI
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
@Published var location: CLLocationCoordinate2D?
override init() {
super.init()
manager.delegate = self
manager.requestWhenInUseAuthorization()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation], didFailWithError error: Error) {
location = locations.first?.coordinate
}
func requestLocation() {
manager.requestLocation()
}
}
以及視圖的代碼(在不同的 Swift 檔案中):
import SwiftUI
import _CoreLocationUI_SwiftUI
struct SettingsView: View {
@StateObject var locationManager = LocationManager()
var body: some View {
NavigationView {
List {
VStack {
if let location = locationManager.location {
Text("Your location: \(location.latitude), \(location.longitude)")
}
LocationButton {
locationManager.requestLocation()
}
.frame(height: 44)
.padding()
}
}
.navigationTitle("Settings")
}
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}
我嘗試重新啟動專案并在物理設備和模擬器上運行構建。當按下 LocationButton 時,兩者都會導致相同的崩潰和輸出。
uj5u.com熱心網友回復:
錯誤是正確的。您尚未實施該locationManager:didUpdateLocations:方法。您有一些名為locationManager:didUpdateLocations:didFailWithError:.
代替:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation], didFailWithError error: Error) {
location = locations.first?.coordinate
}
你需要(洗掉didFailWithError引數):
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location = locations.first?.coordinate
}
如果您希望處理任何錯誤,還可以實作locationManager(_:didFailWithError:)委托方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534865.html
標籤:迅速代码迅捷场地经理
