How can I create a csv file with sensors data in swift 5?

508 Views Asked by At

I have 3 labels inside my view, and this is how I get sensor data and write it inside labels:

func myDeviceMotion(){
        print("Start DeviceMotion")
        motion.deviceMotionUpdateInterval  = 0.5
        motion.startDeviceMotionUpdates(to: OperationQueue.current!) {
            (data, error) in
            print(data as Any)
            if let trueData =  data {

                self.view.reloadInputViews()
                self.xDevi!.text = "x (pitch): \(trueData.attitude.pitch)"
                self.yDevi!.text = "y (roll): \(trueData.attitude.roll)"
                self.zDevi!.text = "z (yaw): \(trueData.attitude.yaw)"
            }
        }
        return
    }

Now I would like to save that date inside a csv file. How can I do that?

I have already tried the solution proposed inside this answer: How to log sensor data and export to CSV?, but it doesn't work for me.

1

There are 1 best solutions below

0
David H On
// Open a new file for writing using FileManager (may have to remove an old one)
let fh: FileHandle = ... // open the file

// Header first (optional)
var s = "Pitch,Roll,Yaw\n" // note no spaces, comma is the operator
fh.writeData(s.data(using: .utf))

// then for each line of dat
s = String(format: "%f,%f,%f\n", trueData.attitude.pitch, trueData.attitude.roll, trueData.attitude.yaw)
fh.writeData(s.data(using: .utf))

// when done, close the file using fh.closefile()