首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检测佩戴Apple Watch的人何时跌倒

检测佩戴Apple Watch的人何时跌倒
EN

Stack Overflow用户
提问于 2018-04-02 07:22:28
回答 1查看 855关注 0票数 1

如果我掉下我的Apple Watch,并在它落地之前接住它,我正在制作的应用程序应该会检测到手表已经掉落。但这是不可能的。下面的代码有什么问题?谢谢!

代码语言:javascript
复制
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()
}
EN

回答 1

Stack Overflow用户

发布于 2018-04-02 09:37:46

motion.deviceMotion将只获取设备运动数据的最新样本。

因此,当您运行它时,它可能只获取一次数据。你可能需要一些像计时器这样的东西来检查加速度。

类似这样的东西(摘自https://developer.apple.com/documentation/coremotion/getting_raw_accelerometer_events)

代码语言:javascript
复制
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)
   }
}

或者,您也可以将处理程序传递给将根据deviceMotionUpdateInterval调用的startDeviceMotionUpdates

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49603547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档