如何在 WatchKit 中使用 CoreMotion?

Posted

技术标签:

【中文标题】如何在 WatchKit 中使用 CoreMotion?【英文标题】:How to use CoreMotion in WatchKit? 【发布时间】:2016-02-22 20:25:38 【问题描述】:

我对这个问题的标题措辞很怀疑,但我认为这就是重点。

我一直试图只读取 WatchKit 上的 CoreMotion 数据,但事实证明,我无法让 startDeviceMotionUpdatesToQueue 工作,我的处理程序从未被调用。

我尝试在自定义后台线程 (NSOperationQueue()) 中运行,但仍然没有成功。

我在真正的 Apple Watch 上调试,而不是模拟器。

在我的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")

输出是

normal stack
normal stack

(是的,两次!我也不知道为什么,但这不是重点,一定是我做错了另一件事)

我在这里发布这个是因为我不知道在哪里查看,这太疯狂了。

【问题讨论】:

【参考方案1】:

Device Motion (startDeviceMotionUpdatesToQueue) 在 WatchOS2 中尚不可用(deviceMotionAvailable 返回 false),可能加速度计可以帮助您startAccelerometerUpdatesToQueue

【讨论】:

感谢您的提醒!那么,WatchOS2 中没有办法读取陀螺仪数据吗? 陀螺仪也不可用,只有加速度计 即使使用 self.motionManager startAccelerometerUpdatesToQueue 也无法正常工作。然而 isAccelerometerAvailable 返回 YES。

以上是关于如何在 WatchKit 中使用 CoreMotion?的主要内容,如果未能解决你的问题,请参考以下文章