【发布时间】:2018-02-22 10:37:15
【问题描述】:
我希望将手表中的实时加速度计和陀螺仪数据推送到相应的 iOS 应用程序,以便在收到数据时进行处理。 我可以通过哪些不同的方式来实现这一目标?
【问题讨论】:
-
为什么这被否决了?
标签: watchkit core-bluetooth apple-watch watchos watchconnectivity
我希望将手表中的实时加速度计和陀螺仪数据推送到相应的 iOS 应用程序,以便在收到数据时进行处理。 我可以通过哪些不同的方式来实现这一目标?
【问题讨论】:
标签: watchkit core-bluetooth apple-watch watchos watchconnectivity
您需要CoreMotion 才能访问加速度计和设备运动数据。
import CoreMotion
let motionManager = CMMotionManager()
if motionManager.isAccelerometerAvailable {
motionManager.accelerometerUpdateInterval = 1
motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: { (data, error) in
if let data = data {
let x = data.acceleration.x
let y = data.acceleration.y
let z = data.acceleration.z
print("x:\(x) y:\(y) z:\(z)")
}
})
}
Apple Watch 上不提供单独的陀螺仪传感器,但Motion Data 提供了更多信息。
let motionManager = CMMotionManager()
if motionManager.isDeviceMotionAvailable {
motionManager.deviceMotionUpdateInterval = 1
motionManager.startDeviceMotionUpdates(to: OperationQueue.current!, withHandler: { (data, error) in
/*
data has many properties like: attitude, gravity, heading etc.
explore, use what you need
*/
})
}
要从 Apple Watch 应用程序向 iPhone 应用程序发送信息,您需要WatchConnectivity。
好教程:https://www.natashatherobot.com/watchconnectivity-say-hello-to-wcsession/
粗略地说,是这样的:
import WatchConnectivity
//this needs to be done just once (on Apple Watch as well as iPhone)
func prepareForWatchConnectivity() {
if (WCSession.isSupported()) {
let session = WCSession.default
session.delegate = self //requires `WCSessionDelegate` protocol, so implement the required delegates as well
session.activate()
}
}
然后您可以通过以下方式从 Apple Watch 向 iPhone App 发送消息:
//Example: Sending Accelerometer Data from Apple Watch
WCSession.default.sendMessage(["x":x,
"y":y,
"z":z],
replyHandler: nil)
在 iPhone 上,您执行相同的操作来设置 WatchConnectivity,但您的代理应在此处处理消息:
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
//message received will be ["x":<value>,"y":<value>,"z":<value>] as sent from Apple Watch
}
上面的 WatchConnectivity 示例是粗略的,只是为了给出一个大致的概念。它很脏,可以大大改进。
【讨论】:
WatchConnectivity 是共享数据的最佳方式。为避免屏幕变暗,您应该使用带有 HKWorkoutSession 的后台任务。见:https://developer.apple.com/library/archive/samplecode/SwingWatch/Listings/SwingWatch_WatchKit_Extension_WorkoutManager_swift.html#//apple_ref/doc/uid/TP40017286-SwingWatch_WatchKit_Extension_WorkoutManager_swift-DontLinkElementID_11
【讨论】: