Shane Shane - 6 months ago 35
Swift Question

swift - get accurate compass heading (magneticHeading and accuracy)

I'm trying to get a single accurate value for a compass heading (which I then use with the gyro/accelerometer to calculate deviance).

Trouble is, if I stop updating the heading after the first result, I'm left with a heading value of 0.0?

I know some location services need to run for a while to give an accurate result, but how to implement this for newHeading.magneticHeading?

Any tips? (I'm using CoreLocation with CLLocation Manager)

func locationManager(manager: CLLocationManager,
didUpdateHeading newHeading: CLHeading) {
referenceHeading = newHeading.magneticHeading
print("New reference heading = \(newHeading.magneticHeading)")
gotReferenceHeading = true
locationManager.stopUpdatingHeading()
}

Answer

I added an if statement based on headingAccuracy, as suggested by @jtbandes.

if newHeading.headingAccuracy > 0 {
    referenceHeading = newHeading.magneticHeading
    gotReferenceHeading = true
    locationManager.stopUpdatingHeading()
}

so I just keep receiving heading updates until I have a useful result.

Comments