如何在swift 5中创建带有传感器数据的csv文件



我的视图中有3个标签,这就是我获取传感器数据并将其写入标签的方式:

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
}

现在我想把这个日期保存在csv文件中。我该怎么做?

我已经尝试了这个答案中提出的解决方案:如何记录传感器数据并导出到CSV?,但这对我不起作用。

// 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,Yawn" // note no spaces, comma is the operator
fh.writeData(s.data(using: .utf))
// then for each line of dat
s = String(format: "%f,%f,%fn", trueData.attitude.pitch, trueData.attitude.roll, trueData.attitude.yaw)
fh.writeData(s.data(using: .utf))
// when done, close the file using fh.closefile()

最新更新