首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将DeviceMotion功能添加到Swift游乐场?

如何将DeviceMotion功能添加到Swift游乐场?
EN

Stack Overflow用户
提问于 2019-03-22 15:00:29
回答 1查看 396关注 0票数 0

我在一个Swift操场上工作,我正在尝试使用这段代码来获得设备的运动。

代码语言:javascript
复制
@objc func update()
{
    if let deviceMotion = motionManager.deviceMotion {
        print("Device Motion Yaw: \(deviceMotion.attitude.yaw)")
    }
}

然而,设备运动似乎不能在Swift游乐场上工作,即使它在iOS中可以工作。如何更改游乐场以支持设备运动?我使用的是一台运行iOS 12的iPad和最新版的Swift Playgrounds和一台Mac机来编写代码。我知道该方法可以完美地调用,当我将其作为iPad和iPhone上的iOS应用程序的一部分时,代码也能完美地运行。根据我的理解,我如何修改一个游乐场来支持它,因为它不是默认的?

EN

回答 1

Stack Overflow用户

发布于 2019-08-20 07:34:24

这是完全有可能的。我已经做过好几次了。您需要一个CMMotionManager类。有很多方法可以做到这一点,但我建议使用计时器。以下是一些示例代码,摘自Apple’s developer documentation,并根据问题进行了修改。

代码语言:javascript
复制
let motion = CMMotionManager()
func startDeviceMotion() {
    if motion.isDeviceMotionAvailable {
        //How often to push updates
        self.motion.deviceMotionUpdateInterval = 1.0/60.0
        self.motion.showsDeviceMovementDisplay = true
        self.motion.startDeviceMotionUpdates(using: .xMagneticNorthZVertical)

        // Configure a timer to fetch the motion data.
        self.timer = Timer(fire: Date(), interval: (1.0 / 60.0), repeats: true,
                           block: { (timer) in
                            if let data = self.motion.deviceMotion {      
let x = data.attitude.pitch
let y = data.attitude.roll
let z = data.attitude.yaw
//Use the data                                
                            }
        })
        RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.default)
    }
}
startDeviceMotionUpdates()

可以这样做,也可以从文档中尝试类似这样的操作

代码语言:javascript
复制
func startQueuedUpdates() {
   if motion.isDeviceMotionAvailable {       self.motion.deviceMotionUpdateInterval = 1.0 / 60.0
      self.motion.showsDeviceMovementDisplay = true
      self.motion.startDeviceMotionUpdates(using: .xMagneticNorthZVertical, 
               to: self.queue, withHandler: { (data, error) in
         // Make sure the data is valid before accessing it.
         if let validData = data {
            // Get the attitude relative to the magnetic north reference frame. 
            let roll = validData.attitude.roll
            let pitch = validData.attitude.pitch
            let yaw = validData.attitude.yaw

            // Use the motion data in your app.
         }
      })
   }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55294421

复制
相关文章

相似问题

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