Onchange of variable in class

Viewed 18

I have a class such as:

class LocationViewModel: NSObject, ObservableObject, CLLocationManagerDelegate {

    @Published var lastSeenLocation: CLLocation?
    @Published var currentPlacemark: CLPlacemark?
    @Published var authorizationStatus: CLAuthorizationStatus

    private let locationManager: CLLocationManager

    override init() {
        locationManager = CLLocationManager()
        authorizationStatus = locationManager.authorizationStatus

        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }

  func requestPermission() {
      locationManager.requestAlwaysAuthorization()
  }

  func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
      authorizationStatus = manager.authorizationStatus
  }
}

I'm trying to check if last seen location = cordinates using this code:

      let radius: Double = 5 // miles

      let userLocation = CLLocation(latitude: locationViewModel.lastSeenLocation?.coordinate.latitude, longitude: locationViewModel.lastSeenLocation?.coordinate.longitude)
      let venueLocation = CLLocation(latitude: 51.500909, longitude: -0.177366)

      let distanceInMeters = userLocation.distanceFromLocation(venueLocation)
      let distanceInMiles = distanceInMeters * 0.00062137

      if distanceInMiles < radius {
          // user is near the venue
      }

The only problem is, that I don't know how to run that code to check constantly. I was thinking .onChange but couldn't figure out how to test for lastSeenlocation in a class. What can I do?

1 Answers

I found a solution here.

For a quick overview:

//I put this code in my LocationViewModel class

    func getUserLocation() {
      locationManager.startUpdatingLocation()
      locationManager.delegate = self
      
    }

  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
      if let location = locations.last {
        print("latitude: \(location.coordinate.latitude), longitude: \(location.coordinate.longitude)")
      }
  }


//I put this code in my ContentView()

    .onAppear {
      locationViewModel.getUserLocation()
    }

Then it prints your latitude & longitude every time your location changes.

Related