Yaoyao
1
import SwiftUI
import CoreMotion
class MotionManager: ObservableObject {
private var motionManager = CMMotionManager()
@Published var deviceMotionData: CMDeviceMotion?
func startUpdates() {
if motionManager.isDeviceMotionAvailable {
motionManager.deviceMotionUpdateInterval = 0.1
motionManager.startDeviceMotionUpdates(to: .main) { [weak self] (motion, error) in
guard let motion = motion, error == nil else { return }
self?.deviceMotionData = motion
}
}
}
func stopUpdates() {
if motionManager.isDeviceMotionAvailable {
motionManager.stopDeviceMotionUpdates()
}
}
}
struct ContentView: View {
@ObservedObject private var motionManager = MotionManager()
var body: some View {
VStack {
if let data = motionManager.deviceMotionData {
Text("Attitude: (pitch: \(data.attitude.pitch), roll: \(data.attitude.roll), yaw: \(data.attitude.yaw))")
Text("Rotation Rate: (x: \(data.rotationRate.x), y: \(data.rotationRate.y), z: \(data.rotationRate.z))")
Text("Gravity: (x: \(data.gravity.x), y: \(data.gravity.y), z: \(data.gravity.z))")
Text("User Acceleration: (x: \(data.userAcceleration.x), y: \(data.userAcceleration.y), z: \(data.userAcceleration.z))")
} else {
Text("Device motion data is not available.")
}
}
.onAppear {
motionManager.startUpdates()
}
.onDisappear {
motionManager.stopUpdates()
}
}
}