我不确定我错过了什么,更新间隔设置似乎没有做任何事情。无论我将其设置为3.0还是0.3,我的数字每秒都会更新几次。我没有看到CPU上升或下降太多,所以它看起来不像iOS剪辑......?最新的Xcode和Swift。
import UIKit
import CoreMotion
class ViewController: UIViewController {
@IBOutlet weak var xlabel: UILabel!
@IBOutlet weak var ylabel: UILabel!
@IBOutlet weak var zlabel: UILabel!
let manager = CMMotionManager()
let queue = OperationQueue()
override func viewDidLoad() {
super.viewDidLoad()
func setLabel(field: CMMagneticField) {
DispatchQueue.main.async {
self.xlabel.text = "\(floor(field.x))"
self.ylabel.text = "\(floor(field.y))"
self.zlabel.text = "\(floor(field.z))"}
}
if manager.isMagnetometerAvailable {
manager.magnetometerUpdateInterval = 3.0
manager.startDeviceMotionUpdates(using: CMAttitudeReferenceFrame.xArbitraryCorrectedZVertical,
to: queue, withHandler: {(data: CMDeviceMotion?, error: Error?) in
if let field = data?.magneticField.field {
setLabel(field: field)}
})} else {
print("I guess there's nothing there")
}
}
}