Answer the question
In order to leave comments, you need to log in
SwiftUI LocationManager how to remove the constant updating of the view?
Hello everyone
There is a code for determining the geolocation:
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 ?? "")") }
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question