Search code examples
iosswiftcore-motion

How to get accelerometer data outside function?


I get x, y, z accelerometer data only inside function.

How to get these values outside too (I'm using real device, an iPhone 4)?

import CoreMotion
//...
var Ax: Double?
var Ay: Double?
var Az: Double?

if motionManager.accelerometerAvailable {
            self.motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue()) {
            (data, error) in
            dispatch_async(dispatch_get_main_queue()) {
                var Ax = data.acceleration.x
                var Ay = data.acceleration.y
                var Az = data.acceleration.z
            }
        }

    } else {
        println("Accelerometer is not available")
    }

println("\(Ax)") // nil value

This is a second version, but with the same result (which one is better, if there is? I need the data of the accelerometer in the background and foreground):

import CoreMotion
//...
var Ax: Double?
var Ay: Double?
var Az: Double?

if motionManager.accelerometerAvailable {
        let queue = NSOperationQueue()
        motionManager.startAccelerometerUpdatesToQueue(queue, withHandler: {(data: CMAccelerometerData!, error: NSError!) in

            var Ax = "\(data.acceleration.x)"
            var Ay = "\(data.acceleration.y)"
            var Az = "\(data.acceleration.z)"
            }
        )

    } else {
        println("Accelerometer is not available")
    }

println("\(Ax)") // nil value

Solution

  • The Ax variable is nil because you redefine Ax, Ay, Az in the handler. Also, the handler is called after the main functions ends, so the print() statement is called before receiving data from the accelerometer. You'll need to refactor your code to take that into consideration, maybe updating the UI in the handler.