返回视图之前,尝试将用户的当前位置存储在ObservableObject类变量中。
struct MapWithLocation: View {
@ObservedObject var event = Event()
@ObservedObject var locationManager = LocationManager()
var body: some View {
let coordinate = self.locationManager.location != nil ? self.locationManager.location!.coordinate : CLLocationCoordinate2D()
//Store this location
event.latitude = coordinate.latitude
event.longitude = coordinate.longitude
return ZStack {
MapView()
Text("\(coordinate.latitude), \(coordinate.longitude)")
}
}
}
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView()
map.showsUserLocation = true
map.delegate = context.coordinator
return map
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func updateUIView(_ uiView: MKMapView, context: Context) {
}
}
只要我注释掉设置event.latitude和event.longitude(定义为CLLocationDegrees)的两行,该方法就可以很好地工作。但是,当我取消注释这些行时,“文本”视图将显示正确的坐标,并带有空白地图,如下图所示。知道发生了什么事吗?
编辑:这是一种将用户当前位置存储在ObservableObject类变量中的方法。 (请注意,您还需要修改Info.plist)
import Foundation
import SwiftUI
import MapKit
class Event: ObservableObject {
@Published var latitude: Double = 0.0
@Published var longitude: Double = 0.0
}
class LocationManager {
var locationManager = CLLocationManager()
func getUserLocation(into event: Event) {
let status = CLLocationManager.authorizationStatus()
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
if status == .authorizedAlways || status == .authorizedWhenInUse {
if CLLocationManager.locationServicesEnabled() {
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.locationManager.startUpdatingLocation()
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
if let theLocation = self.locationManager.location {
event.latitude = theLocation.coordinate.latitude
event.longitude = theLocation.coordinate.longitude
}
})
}
}
}
}
struct ContentView: View {
@ObservedObject var event = Event()
var locationManager = LocationManager()
var body: some View {
ZStack {
MapView().edgesIgnoringSafeArea(.vertical)
Text("\(event.latitude), \(event.longitude)")
}.onAppear(perform: { self.locationManager.getUserLocation(into: self.event) })
}
}
struct MapView: UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView()
map.showsUserLocation = true
map.delegate = context.coordinator
return map
}
func makeCoordinator() -> Coordinator { Coordinator(self) }
func updateUIView(_ uiView: MKMapView, context: Context) { }
final class Coordinator: NSObject, MKMapViewDelegate {
var control: MapView
init(_ control: MapView) {
self.control = control
}
}
}