Sensor Data information is now available in Watchkit for watchOS 2.0
.
You could check this information in the following session which is total 30 minutes presentation.If you do not want to watch entire session, then you directly jump to the CoreMotion
and HealthKit
features which is in between 22-28 min:
WatchKit for watchOS 2.0 Session in WWDC 2015
Heart Rate Implementation
https://developer.apple.com/documentation/healthkit/hkworkout
Accelerometer Implementation
Here is the implementation of accelerometer in WatchKit Extension, Here is the reference:
import WatchKit
import Foundation
import CoreMotion
class InterfaceController: WKInterfaceController {
@IBOutlet weak var labelX: WKInterfaceLabel!
@IBOutlet weak var labelY: WKInterfaceLabel!
@IBOutlet weak var labelZ: WKInterfaceLabel!
let motionManager = CMMotionManager()
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
motionManager.accelerometerUpdateInterval = 0.1
}
override func willActivate() {
super.willActivate()
if (motionManager.accelerometerAvailable == true) {
let handler:CMAccelerometerHandler = {(data: CMAccelerometerData?, error: NSError?) -> Void in
self.labelX.setText(String(format: "%.2f", data!.acceleration.x))
self.labelY.setText(String(format: "%.2f", data!.acceleration.y))
self.labelZ.setText(String(format: "%.2f", data!.acceleration.z))
}
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: handler)
}
else {
self.labelX.setText("not available")
self.labelY.setText("not available")
self.labelZ.setText("not available")
}
}
override func didDeactivate() {
super.didDeactivate()
motionManager.stopAccelerometerUpdates()
}
}
Code for WatchOS 7.x
import WatchKit
import Foundation
import CoreMotion
class InterfaceController: WKInterfaceController {
@IBOutlet weak var labelX: WKInterfaceLabel!
@IBOutlet weak var labelY: WKInterfaceLabel!
@IBOutlet weak var labelZ: WKInterfaceLabel!
let motionManager = CMMotionManager()
override func awake(withContext context: Any?) {
super.awake(withContext: context)
motionManager.accelerometerUpdateInterval = 0.1
}
override func willActivate() {
super.willActivate()
if (motionManager.isAccelerometerAvailable == true) {
let handler:CMAccelerometerHandler = {data,error in
self.labelX.setText(String(format: "%.2f", data!.acceleration.x))
self.labelY.setText(String(format: "%.2f", data!.acceleration.y))
self.labelZ.setText(String(format: "%.2f", data!.acceleration.z))
}
motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: handler)
}
else {
self.labelX.setText("not available")
self.labelY.setText("not available")
self.labelZ.setText("not available")
}
}
override func didDeactivate() {
super.didDeactivate()
motionManager.stopAccelerometerUpdates()
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…