如果我放下我的Apple Watch并在它撞到地面之前抓住它,我正在制作的应用程序会检测到手表已经掉落。但那并没有发生。下面的代码有什么问题?谢谢!
let motion = CMMotionManager()
if motion.isDeviceMotionAvailable {
motion.deviceMotionUpdateInterval = 0.1
motion.startDeviceMotionUpdates()
if let deviceMotion = motion.deviceMotion {
let accelerationX = deviceMotion.gravity.x + deviceMotion.userAcceleration.x
let accelerationY = deviceMotion.gravity.y + deviceMotion.userAcceleration.y
let accelerationZ = deviceMotion.gravity.z + deviceMotion.userAcceleration.z
let totalAcceleration = sqrt((accelerationX * accelerationX) + (accelerationY * accelerationY) + (accelerationZ * accelerationZ))
if totalAcceleration > 9.0 {
print("Watch has fallen")
}
}
motion.stopDeviceMotionUpdates()
}
答案 0 :(得分:1)
motion.deviceMotion
将获取最新的设备运动数据样本。
因此,这可能只是在您运行数据时获取数据。你可能需要像计时器这样的东西来检查加速度。
这样的事情(取自https://developer.apple.com/documentation/coremotion/getting_raw_accelerometer_events)
let motion = CMMotionManager()
func startAccelerometers() {
// Make sure the accelerometer hardware is available.
if self.motion.isAccelerometerAvailable {
self.motion.accelerometerUpdateInterval = 1.0 / 60.0 // 60 Hz
self.motion.startAccelerometerUpdates()
// Configure a timer to fetch the data.
self.timer = Timer(fire: Date(), interval: (1.0/60.0),
repeats: true, block: { (timer) in
// Get the accelerometer data.
if let data = self.motion.accelerometerData {
let x = data.acceleration.x
let y = data.acceleration.y
let z = data.acceleration.z
// Use the accelerometer data in your app.
}
})
// Add the timer to the current run loop.
RunLoop.current.add(self.timer!, forMode: .defaultRunLoopMode)
}
}
或者,您也可以将处理程序传递给startDeviceMotionUpdates
,该处理程序将根据deviceMotionUpdateInterval
进行调用。