如何获取 Swift 中 iPhone 的当前俯仰、偏航和横滚?

How can I get the current pitch, yaw and roll of the iPhone in Swift?

我正在寻找 iPhone 设备相对于基本位置的准确当前俯仰、偏航和滚动。很像在 Compass App 中所做的事情。我在网上找到的大部分内容都是关于检测结果中的 变化 ,而我正在寻找相对于基本位置的绝对位置,基本位置 (pitch: 0, roll: 0, yaw: 0) 就是这个位置:

任何人都可以建议我应该怎么做才能得到这个吗?我需要这个一次性的,基本上是函数调用的结果。

设备不会持续跟踪方向。您的应用需要表明它需要此数据(通过 Info.plist 文件)并在您可以访问它之前开始监控它。

可通过 CMMotionManager class 的 deviceMotion 属性 访问信息。可选,表示如果设备不支持,或者你没有提前开始监控数据,则为nil。

您需要为 startDeviceMotionUpdates(using:) 指定可用于此目的的参考系,以便获得正确的值。你要的大概是.xTrueNorthZVertical。请注意,此文档指出:

Note that using this reference frame may require device movement to calibrate the magnetometer. It also requires the location to be available in order to calculate the difference between magnetic and true north.

这可能意味着你不能自发地阅读它。您可能需要在您的应用程序启动或用户进入您需要的视图时开始监视,并在校准完成并且用户执行某些需要它的操作后检查该值。