尝试使用新的 Swift @Observable 来监控 SwiftUI 内容视图中的 GPS 位置。但如何将最新位置与 SwiftUI 地图的 mapCameraPosition 关联起来?
理想情况下答案可以涵盖:
请参阅我嵌入在下面的代码中的错误。
import SwiftUI
import MapKit
@Observable
final class NewLocationManager : NSObject, CLLocationManagerDelegate {
var location: CLLocation? = nil
private let locationManager = CLLocationManager()
func startCurrentLocationUpdates() async throws {
if locationManager.authorizationStatus == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
for try await locationUpdate in CLLocationUpdate.liveUpdates() {
guard let location = locationUpdate.location else { return }
self.location = location
}
}
}
struct ContentView: View {
var newlocationManager = NewLocationManager()
@State private var cameraPosition: MapCameraPosition = .region(MKCoordinateRegion(
center: newlocationManager.location?.coordinate ?? <#default value#>,
span: MKCoordinateSpan(latitudeDelta: 0.25, longitudeDelta: 0.25)
))
// GET ERROR: Cannot use instance member 'newlocationManager' within property initializer; property initializers run before 'self' is available
var body: some View {
ZStack {
Map(position: $cameraPosition)
Text("New location manager: \(newlocationManager.location?.description ?? "NIL" )") // works
}
.task {
try? await newlocationManager.startCurrentLocationUpdates()
}
}
}
#Preview {
ContentView()
}
正如错误所述,您无法使用
newlocationManager
在视图初始化完成之前。
尝试使用
.onAppear{...}
,如示例代码所示。
struct ContentView: View {
@State var newlocationManager = NewLocationManager() // <--- here
@State private var cameraPosition: MapCameraPosition = .region(MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 35.68, longitude: 139.75), // <--- here, adjust
span: MKCoordinateSpan(latitudeDelta: 0.25, longitudeDelta: 0.25)
))
var body: some View {
ZStack {
Map(position: $cameraPosition)
Text("New location manager: \(newlocationManager.location?.description ?? "NIL" )") // works
}
.task {
try? await newlocationManager.startCurrentLocationUpdates()
}
.onAppear { // <--- here
cameraPosition = .region(MKCoordinateRegion(
center: newlocationManager.location?.coordinate
?? CLLocationCoordinate2D(latitude: 35.68, longitude: 139.75),
span: MKCoordinateSpan(latitudeDelta: 0.25, longitudeDelta: 0.25)
))
}
}
}