我在一个Swift操场上工作,我正在尝试使用这段代码来获得设备的运动。
@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应用程序的一部分时,代码也能完美地运行。根据我的理解,我如何修改一个游乐场来支持它,因为它不是默认的?
发布于 2019-08-20 07:34:24
这是完全有可能的。我已经做过好几次了。您需要一个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.
}
})
}
}https://stackoverflow.com/questions/55294421
复制相似问题