SWIFTUI 和 Core Motion
Posted
技术标签:
【中文标题】SWIFTUI 和 Core Motion【英文标题】:SWIFTUI and Core Motion 【发布时间】:2020-05-26 10:46:59 【问题描述】:我正在尝试在 SWIFTUI 视图中显示加速度计数据。此代码可以打印到控制台,但我不明白如何在视图中获取它,因此我可以在 SWIFTUI 中使用它。
import SwiftUI
import CoreMotion
struct AccelerometerView: View
let motionManager = CMMotionManager()
let queue = OperationQueue()
var body: some View
VStack
Text("accelerate:").onAppear
print("ON APPEAR")
self.motionManager.startDeviceMotionUpdates(to: self.queue) (data: CMDeviceMotion?, error: Error?) in
guard let data = data else
print("Error: \(error!)")
return
let attitude: CMAttitude = data.attitude
print("pitch: \(attitude.pitch)")
print("yaw: \(attitude.yaw)")
print("roll: \(attitude.roll)")
//.onappear
//Text("Pitch:\(attitude.pitch)")
//Vstack
//view
//struct
struct AccelerometerView_Previews: PreviewProvider
static var previews: some View
AccelerometerView()
【问题讨论】:
【参考方案1】:这是可能的解决方案
struct AccelerometerView: View
let motionManager = CMMotionManager()
let queue = OperationQueue()
@State private var pitch = Double.zero
@State private var yaw = Double.zero
@State private var roll = Double.zero
var body: some View
VStack
Text("Pitch: \(pitch)")
Text("Yaw: \(yaw)")
Text("Roll: \(roll)")
//Vstack
.onAppear
print("ON APPEAR")
self.motionManager.startDeviceMotionUpdates(to: self.queue) (data: CMDeviceMotion?, error: Error?) in
guard let data = data else
print("Error: \(error!)")
return
let attitude: CMAttitude = data.attitude
print("pitch: \(attitude.pitch)")
print("yaw: \(attitude.yaw)")
print("roll: \(attitude.roll)")
DispatchQueue.main.async
self.pitch = attitude.pitch
self.yaw = attitude.yaw
self.roll = attitude.roll
//.onappear
//view
//struct
【讨论】:
行得通!你能解释一下 DispatchQueue 是如何工作的吗?非常感谢您的快速回复。 Dispatch Queue 是一个对象,用于管理应用程序主线程或后台线程上的串行或并发执行。在这种情况下,CoreMotion 的回调是一个后台线程,因此您需要在主线程中更新 vars(UI 更新总是必须在主线程中完成)以上是关于SWIFTUI 和 Core Motion的主要内容,如果未能解决你的问题,请参考以下文章
使用 SwiftUI 2.0 和 Core Data 预填充数据
SwiftUI:Core Data @FetchRequest 和 List 显示托管对象 - 在 lockscreemn 上丢失数据