iOS Core Motion Accessing Barometer to get relative altitude

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Swift

Import the Core Motion library:

import CoreMotion

Next, we need to create a CMAltimeter object, but a common pitfall is to create it in the viewDidLoad(). If done that way, the altimeter won’t be accessible when we need to call a method on it. Nevertheless, go ahead and create your CMAltimeter object just before the viewDidLoad():

let altimeter = CMAltimeter()

Now:

  1. We need to check if relativeAltitude is even available with the following method: CMAltimeter.isRelativeAltitudeAvailable.

  2. If that returns true, you can then begin monitoring altitude change with startRelativeAltitudeUpdatesToQueue

  3. If there are no errors, you should be able to retrieve data from the relativeAltitude and pressure properties.

Given below is the definition of a button action to begin monitoring with our barometer.

@IBAction func start(sender: AnyObject){
if CMAltimeter.isRelativeAltitudeAvailable() {
    // 2
    altimeter.startRelativeAltitudeUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { data, error in
        // 3
        if (error == nil) {
            println("Relative Altitude: \(data.relativeAltitude)")
            println("Pressure: \(data.pressure)")
        }
    })
}


Got any iOS Question?