import UIKit
import ARKit
import PlaygroundSupport
import SceneKit
import CoreMotion
class MyViewController: UIViewController {
let motionManager = CMMotionManager()
var timer: Timer!
var label = UILabel(frame: CGRect(x: 50, y: 400, width: 400, height: 100))
override func loadView() {
let view = UIView()
view.addSubview(label)
label.text = "Show Yaw Here"
self.view = view
view.backgroundColor = .white
motionManager.startAccelerometerUpdates()
motionManager.startGyroUpdates()
motionManager.startMagnetometerUpdates()
motionManager.startDeviceMotionUpdates()
timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(MyViewController.update), userInfo: nil, repeats: true)
}
@objc func update() {
self.label.text = "Obama"
if let accelerometerData = motionManager.accelerometerData {
print("Device Accelerometer: \(accelerometerData)")
}
if let gyroData = motionManager.gyroData {
print("Device Gyro: \(gyroData)")
}
if let magnetometerData = motionManager.magnetometerData {
print("Device Magnetometer: \(magnetometerData)")
}
if let deviceMotion = motionManager.deviceMotion {
print("Device Motion: \(deviceMotion)")
let yaw = (Int)(Double(floor(1000*deviceMotion.attitude.yaw)/1000) * 180.0/Double.pi)
self.label.text = "Yaw: \(yaw) Degrees"
}
}
}
PlaygroundPage.current.liveView = MyViewController()
这(上面)是我用作游乐场的代码。我直接从iOS应用程序获取了代码,当我在同一设备上运行iOS应用程序时,它可以完美运行,这是从2018年初开始运行iOS 12的iPad。这是我用于实际应用程序的代码,可以在iPad。它所做的只是将以度为单位的“偏航”值写入文本框。当我运行它们中的任何一个时,我都没有收到错误或警告。视图控制器确实会显示在操场上,初始标签文本也会显示在屏幕上,但是当我移动iPad时,代码不会更新设备的运动,而在应用程序版本中却会更新。
import UIKit
import CoreMotion
class ViewController: UIViewController {
let motionManager = CMMotionManager()
var timer: Timer!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label.text = "ayy lmao"
motionManager.startAccelerometerUpdates()
motionManager.startGyroUpdates()
motionManager.startMagnetometerUpdates()
motionManager.startDeviceMotionUpdates()
timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
}
@objc func update() {
if let accelerometerData = motionManager.accelerometerData {
print("Device Accelerometer: \(accelerometerData)")
}
if let gyroData = motionManager.gyroData {
print("Device Gyro: \(gyroData)")
}
if let magnetometerData = motionManager.magnetometerData {
print("Device Magnetometer: \(magnetometerData)")
}
if let deviceMotion = motionManager.deviceMotion {
print("Device Motion: \(deviceMotion)")
let yaw = (Int)(deviceMotion.attitude.yaw * 180.0/Double.pi)
self.label.text = "Yaw: \(yaw) Degrees"
}
}
}
答案 0 :(得分:0)
核心位置API是异步的,因此您必须在调用startUpdatingLocation()之后保持游乐场运行。因此,旋转一下
PlaygroundPage.current.needsIndefiniteExecution = true
有关needsindefiniteExecution的更多信息
答案 1 :(得分:0)
Core Motion框架可以在iPad上的Swift Playgrounds
应用程序上对Device Motion以外的所有其他设备正常运行。 StartDeviceMotionUpdates(to:){}
无法交付任何更新。遗憾的是,我没有找到关于为什么应该这样做的解释!当然,只能通过CoreLocation
来访问GPS,这需要应用程序不提供安全性验证,因此也无法访问GPS数据。