Search code examples
ioswatchkitcore-motion

How to use CoreMotion in WatchKit?


I was quite dubious on this question's title phrasing, but I think that's the whole point as it is.

I've been trying to just read the CoreMotion data on the WatchKit, but as it turns out, I can't get startDeviceMotionUpdatesToQueue to work, my handler is never called.

I tried running in a custom background thread (NSOperationQueue()), still no luck.

I'm debugging on a real Apple Watch, not the simulator.

In my WKInterfaceController:

let manager = CMMotionManager()

override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)
    let communicator = SessionDelegate()
    manager.deviceMotionUpdateInterval = 1 / 60
    manager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue()) {
        (motionerOp: CMDeviceMotion?, errorOp: NSError?) -> Void in
        print("got into handler")
        guard let motion = motionerOp else {
            if let error = errorOp {
                print(error.localizedDescription)
            }
            assertionFailure()
            return
        }
        print("passed guard")
        let roll = motion.attitude.roll
        let pitch = motion.attitude.pitch
        let yaw = motion.attitude.yaw
        let attitudeToSend = ["roll": roll, "pitch": pitch, "yaw": yaw]
        communicator.send(attitudeToSend)
    }

    print("normal stack")
}

the output is

normal stack
normal stack

(Yes, twice! I don't know why that either, but that is not the point, must be another thing I'm doing wrongly)

I'm posting this here 'cause I have no clue to where look into, this is freaking crazy.


Solution

  • Device Motion (startDeviceMotionUpdatesToQueue) is not available in WatchOS2 yet (deviceMotionAvailable returns false), probably accelerometer can help you startAccelerometerUpdatesToQueue