iosswiftswift3cmmotionmanager

Swift 2 to Swift 3.0 motionManager


I am converting an app from swift 2 to swift 3 and I'm trying to use the CMMotionManager, but it gives me this error when I try to call the .startAccelerometerUpdates() function... No clue what's wrong though.

This is how I initialize the manager:

let motionManager = CMMotionManager()

Trying to call the function:

    motionManager.startAccelerometerUpdates(to: OperationQueue.main) { [weak self] (data: CMAccelerometerData?, error: NSError?) in
        self!.outputAccelerationData(data!.acceleration)
    }

Error: Cannot convert value of type '(CMAccelerometerData?, NSError?) -> ()' to expected argument type 'CMAccelerometerHandler' (aka '(Optional, Optional) -> ()')

Thanks!


Solution

  • The cryptic error message boils down to this: in Swift 3 NSError is bridged to Error instead. Write your code like this and the problem should go away:

    motionManager.startAccelerometerUpdates(to: OperationQueue.main) { [weak self] (data: CMAccelerometerData?, error: Error?) in