我的应用程序取决于 iPhone 的握持方式。由于多种原因,我需要使用具有
CoreMotion
和 .attitude
属性的设备传感器。当用户为我的应用程序设置配置时,仅使用几次/几秒钟读取设备的姿态。
我尝试了拉和推运动数据。在这两种情况下,我无法弄清楚如何以允许我在其他地方访问它们的方式存储
CMAttitude
值。
在下面的代码中...
print
闭包内的manager.startDeviceMotionUpdates
语句工作正常。.attitude
值的访问权限为零。TextView
,Xcode 预览会崩溃,并且在我的设备上运行的应用程序也会崩溃。import SwiftUI
import CoreMotion
let manager = CMMotionManager()
let queue = OperationQueue()
struct ContentView: View {
@State var myAttitude: CMAttitude = CMAttitude()
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
Button(action: {
guard manager.isDeviceMotionAvailable else { return }
manager.startDeviceMotionUpdates(to: queue) { (motion, error) in
guard let motion else {
return
}
let currentAttitude = motion.attitude
myAttitude = currentAttitude
print("🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢")
print("Attitude-Pitch: \(myAttitude)")// ←←← These Work Fine!
print("Attitude-Pitch: \(myAttitude.pitch.formatted(.number.precision(.fractionLength(5))))")
print("Attitude-Yaw: \(myAttitude.yaw.formatted(.number.precision(.fractionLength(5))))")
print("Attitude-Roll: \(myAttitude.roll.formatted(.number.precision(.fractionLength(5))))")
print("🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴")
}
}, label: {
Text("Check Your Attitude")
.foregroundStyle(.cyan)
})
Text("Attitude-Pitch: \(myAttitude)") // ←←← App Crashes Here!
// Text("Attitude-Pitch: \(myAttitude.pitch.formatted(.number.precision(.fractionLength(5))))")
// Text("Attitude-Yaw: \(myAttitude.yaw.formatted(.number.precision(.fractionLength(5))))")
// Text("Attitude-Roll: \(myAttitude.roll.formatted(.number.precision(.fractionLength(5))))")
}
.padding()
}
}
#Preview {
ContentView(myAttitude: CMAttitude())
}
更新主队列中的状态:
DispatchQueue.main.async {
myAttitude = currentAttitude
}