我的应用程序依赖于iPhone的握持方式。出于多种原因,我需要使用带有CoreMotion
和.attitude
属性的设备传感器。当用户为我的应用程序设置配置时,阅读设备的姿态只会使用几次/秒。
我已经尝试了pull和push两种方法来处理运动数据,但我都不知道如何存储CMAttitude
的值,以便在其他地方访问它们。
在下面的代码中...
manager.startDeviceMotionUpdates
闭包中的print
语句工作正常。- 但是.我不能访问闭包外的
.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())
}
字符串
3条答案
按热度按时间velaa5lx1#
你的代码有两个问题
@State
应该始终标记为private
,因为memberwise初始化器被认为是不安全的。https://developer.apple.com/documentation/swiftui/state
1.当
CMAttitude()
编译时,它没有文档,所以你不应该使用它。它来自NSObject
,它并不真正属于CMAttitude
(这是一个bug)。https://developer.apple.com/documentation/coremotion/cmattitude的
一旦你纠正了这两个问题,你的代码将不再崩溃。
字符串
wb1gzix02#
你能试试这个吗?我认为你可以修改@State变量,CAAtutyde类型可能是一个问题。
字符串
bvhaajcl3#
nil
作为默认值字符串
并更新主队列中的状态:
型