Search code examples
iosswiftcsvexport-to-csv

How to log sensor data and export to CSV?


I have an iOS app that prints sensor data (gyroscope, attitude, acceleration, etc.) to the terminal at ~50Hz with CoreMotion. I want to save the sensor readings and export them to a csv file. Which frameworks, if any, would I use to do this? I've been trying to use Core Data but I feel like it's not the correct tool to use.

for reference, this is how I read accelerometer data:

func startAccel() ->Void{ //Starting accelerometer
    motionManager.accelerometerUpdateInterval = 1.0 / Double(hz)
    motionManager.startAccelerometerUpdates(to: OperationQueue.current!){ (data, error) in
        if let myData = data{
            let x = myData.acceleration.x
            let y = myData.acceleration.y
            let z = myData.acceleration.z
            print("Acceleration X: \(x) Y: \(y) Z: \(z)")
        }
    }
}

Solution

  • All you have to do to create a CSV file is create a string with commas separating your columns, and newlines separating your rows, then write the string to a file.

    let csvString = allData
        .map { "\($0.x),\($0.y),\($0.z)" }
        .joined(separator: "\n")
    csvString.write(toFile: "some-file.csv", atomically: true, encoding: .utf8)