我正在Swift操场上工作,我试图使用此代码来获取:
@objc func update()
{
if let deviceMotion = motionManager.deviceMotion {
print("Device Motion Yaw: \(deviceMotion.attitude.yaw)")
}
}
但是,即使Motion设备可以在iOS上运行,它似乎也无法在Swift操场上运行。我将如何改变运动场以支持设备运动?我正在使用运行iOS 12的iPad和最新版本的Swift游乐场以及使用Mac的代码。我知道该方法被完美调用,并且当我将它作为iPad和iPhone上的iOS应用程序的一部分放置时,代码可以完美运行。据我了解,默认情况下,我不会修改游乐场以支持此操作。
答案 0 :(得分:0)
完全有可能。我已经做过几次了。您需要一个CMMotionManager
类。有很多方法可以做到这一点,但我建议您使用计时器。这是一些示例代码,摘自Apple’s developer documentation,并经过修改以适合该问题。
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()
要么这样做,要么尝试类似的方法,同样可以从文档中获得
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.
}
})
}
}