Using the Altimeter on iPhone 6S with Swift

I was playing around with the new xcode 7.2 which allows you to beta test applications on your own phone without an Apple developer account.  Add to that the barometer available on the iPhone 6s and I just wanted to see how hard it was to write an app that can show you your altitude.

This seems like it would be pretty straightforward but it turns out there’s practically zero documentation on how to use the altimeter, and for a Swift newbie, this turned out to be quite a problem.

All I wanted to do was create an app with one button to start the altimeter, and a label which constantly updated with the relative altitude.  It seemed like something that might take an hour or two max.  However, with the incomplete solutions available and cryptic problems with refreshing the display while in a closure, it became much harder than I ever anticipated.

Which is why I’m publishing the code, however amateur, because it does actually work.

@IBOutlet weak var altitudeLabel: UILabel!

lazy var altimeter = CMAltimeter()
lazy var queue = NSOperationQueue()

@IBAction func trackButton(sender: UIButton) {

 if CMAltimeter.isRelativeAltitudeAvailable() {

    altimeter.startRelativeAltitudeUpdatesToQueue(
        queue, 
        withHandler: {( data: CMAltitudeData?, 
                       error: NSError?) in

    // Needed to refresh the screen 
    // from inside the closure
    dispatch_async(dispatch_get_main_queue(), {
        self.altitudeLabel.text = 
           String("%.2f feet",
           ((3.28 * 
           ((data?.
             relativeAltitude.doubleValue))!)))
        })
    })
  } else {
    self.altitudeLabel.text = 
       "No barometer available"
  }
}

It did finally work and looks like this:

AltimeterScreen