D
D
Denis Antukh2020-08-26 15:09:40
iOS
Denis Antukh, 2020-08-26 15:09:40

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
      }
    })
  }
}


The view uses:

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 ?? "")") }
   }
}


Having obtained that with such code, SomeView is constantly updated.
What can be changed to prevent this from happening?

As I understand it, the problem is in didUpdateLocations.
I don't know how to bypass it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Antukh, 2020-08-26
@antyxweb

Solution:
Moved objectWillChange.send() to loadImage function

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question