How to get altitude with startMonitoringSignificantLocationChanges in swift 5?

I am using CoreLocation in my application. I want to track significant changes in location and altitude. So I have used startMonitoringSignificantLocationChanges, but not getting altitude.

Here is my code :
Code Block
public class MyLocationManager: NSObject {
public var currentLocation = CLLocation()
private var locationManager = CLLocationManager()
public override init() {
        super.init()
        self.configureLocationManager()
    }
private func configureLocationManager() {
        self.locationManager.delegate = self
self.locationManager.pausesLocationUpdatesAutomatically = false
        self.locationManager.allowsBackgroundLocationUpdates = true
self.locationManager.requestAlwaysAuthorization()
    }
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        self.currentLocation = locations.last ?? CLLocation()
        let lat: Double = self.currentLocation.coordinate.latitude
        let long: Double = self.currentLocation.coordinate.longitude
        let alt: Double = self.currentLocation.altitude
        let dateTime = self.currentLocation.timestamp
        print("\n\nLatitude :---- \(lat)")
        print("Longitude :---- \(long)")
        print("Altitude :---- \(alt)")
        print("Date :---- \(dateTime)")
}
}

  1. Then I run app.

  2. Allow location for Always

  3. Check for location update (Location is updating but not getting altitude)

  4. Sent app in background (Location is updating but not getting altitude)

  5. Kill app / Full closed / Remove from background / Terminated (Location is not updating sometime and not getting altitude)

Can anyone help me with this problem?





Replies

Hmmm...if you have a valid CLLocation object and are outside within range of a GPS satellite, you should have a value for currentLocation.altitude. Perhaps it's a cached value where altitude wasn't available?

You may want to run a test that takes the significant location change API out of the mix by adding a button to trigger an explicit location request via locationManager.requestLocation(), then walk outside, tap the button, and see what you get.

This just worked for me:

Code Block    
@IBAction func getCurrentLocationTapped(_ sender: Any) {
/* request location data for one-off usage */
self.locationManager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
/* the last element is the most recent location */
if let location = locations.last {
latitudeLabel.text = "\(location.coordinate.latitude)"
longitudeLabel.text = "\(location.coordinate.longitude)"
altitudeLabel.text = "\(location.altitude)"
}
}