0Accessing Barometer to get relative altitude

suggest change

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)")
        }
    })
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Core Motion:
* 0Accessing Barometer to get relative altitude

Table Of Contents
12 UIView
15 UIColor
26 UIImage
28 CALayer
30 NSDate
40 iBeacon
49 NSTimer
79 NSURL
87 AWS SDK
96 NSData
101 Segues
104 EventKit
105 NSBundle
106 SiriKit
111 StoreKit
117 3D Touch
119 Keychain
122 Block
141 AirDrop
144 UISlider
145 Carthage
146 HealthKit
149 Core Motion
151 plist
157 MVVM
164 UIPhoenix
166 Simulator
168 NSArray
169 OpenGL
175 Core Data
179 MyLayout
180 UIFont
189 Security
200 Codable