Привет всем
Есть код для определения геопозиции:
import Foundation
import CoreLocation
import Combine
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
self.status = status
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
self.location = location
self.geocode()
}
}
class LocationManager: NSObject, ObservableObject {
private let locationManager = CLLocationManager()
private let geocoder = CLGeocoder()
let objectWillChange = PassthroughSubject<Void, Never>()
@Published var status: CLAuthorizationStatus? {
willSet { objectWillChange.send() }
}
@Published var location: CLLocation? {
willSet { objectWillChange.send() }
}
override init() {
super.init()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
@Published var placemark: CLPlacemark? {
willSet { objectWillChange.send() }
}
private func geocode() {
guard let location = self.location else { return }
geocoder.reverseGeocodeLocation(location, completionHandler: { (places, error) in
if error == nil {
self.placemark = places?[0]
} else {
self.placemark = nil
}
})
}
}
В вьюхе используется:
struct SomeView: View {
@ObservedObject var lm = LocationManager()
var body: some View { // }
func loadImage() {
var locationLatitude: String { return("\(lm.location?.coordinate.latitude ?? 0)") }
var locationLongitude: String { return("\(lm.location?.coordinate.longitude ?? 0)") }
var locationName: String { return("\(lm.placemark?.name ?? "")") }
var locationLocality: String { return("\(lm.placemark?.locality ?? "")") }
var locationCountry: String { return("\(lm.placemark?.country ?? "")") }
var locationPlacemark: String { return("\(lm.placemark?.description ?? "")") }
}
}
Получестя, что при таком коде SomeView постоянно обновляется.
Что изменить, чтобы этого не происходило?
Я как понял, что проблема в didUpdateLocations.
Как это обойти не знаю