Search code examples
swiftuicore-motion

SWIFTUI and Core Motion


I am trying to display the accelerometer data in a SWIFTUI view. This code works to print to the console, but I can't understand how to get it inside a view so I can use it in 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()
    }
}

Solution

  • Here is possible solution

    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