Reputation: 29
I want the realtime accelerometer and gyro data from the watch to be pushed to the corresponding iOS app in order to process the data as and when received. What are the different ways i can achieve this?
Upvotes: 1
Views: 3519
Reputation: 11
WatchConnectivity is the best way to share data. To avoid screen dimming, you should use background task with HKWorkoutSession. see: 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
Upvotes: 0
Reputation: 20234
You would require CoreMotion
to access the accelerometer & device motion data.
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)")
}
})
}
Gyroscope sensor alone is not available on Apple Watch but Motion Data
is with more information.
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
*/
})
}
For sending the information from Apple Watch app to iPhone app counterpart, you would require WatchConnectivity
.
Good Tutorial: https://www.natashatherobot.com/watchconnectivity-say-hello-to-wcsession/
In a very rough manner, it would be something like:
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()
}
}
Then you can send messages from Apple Watch to iPhone App simply by:
//Example: Sending Accelerometer Data from Apple Watch
WCSession.default.sendMessage(["x":x,
"y":y,
"z":z],
replyHandler: nil)
On the iPhone you do the same thing to set up WatchConnectivity but here your delegate should handle the message in:
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
//message received will be ["x":<value>,"y":<value>,"z":<value>] as sent from Apple Watch
}
The above WatchConnectivity example is rough and just for giving a general idea. It's dirty and can be structured and improved greatly.
Upvotes: 2