Search code examples
iosswiftcore-motion

Why am I not getting any accelerometer update?


I am trying to get accelerometer updates with CoreMotion and Swift, here is what I placed in my viewDidLoad :

override func viewDidLoad() {
    super.viewDidLoad()
    let motionManager = CMMotionManager()
    motionManager.accelerometerUpdateInterval = 0.2
    motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()) {
        (info:CMAccelerometerData!,error:NSError!) in
        if error != nil {
            println(error)
        }
        else {
            println("OK")
        }
    }
}

The problem is that it looks like my closure never gets called (I don't have anything in the console), do you know why?


Solution

  • The problem is that the variable motionManager, to which your CMMotionManager instance is assigned, is declared as a local variable (in the body of the function viewDidLoad), which means that it goes out of existence when the function finishes executing. Therefore its lifetime is about a 10000th of a second.

    Well, that is not long enough for your CMMotionManager to obtain very many updates!