I have an app that can export user input information in a csv file. I set the file name to be PatientInfo in the code. However when I receive new data and click save again. The old one will be overwritten. How to automatically create a new csv file with a name perhaps PatientInfo_01? Or even better, let the user type in the file name after clicking save button.
This is the original code I have:
var patientsData:[Dictionary<String, AnyObject>] = Array()
var dct = Dictionary<String, AnyObject>()
func createCSVX(from recArray:[Dictionary<String, AnyObject>]) {
var csvString = "\("Time"),\("Force")\n"
dct.updateValue(-TestDraw.time as AnyObject, forKey: "T")
for i in 0...TestDraw.force.count-1 {
dct.updateValue(TestDraw.force[i] as AnyObject, forKey: "F")
patientsData.append(dct)
csvString = csvString.appending("\(String(describing: dct["T"]!)), \(String(describing: dct["F"]!))\n")
}
let fileManager = FileManager.default
do {
let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil, create: false)
let fileURL = path.appendingPathComponent("PatientInfo.csv")
try csvString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
print("error creating file")
}
}
Try this:
var counter = 0
let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil, create: false)
let fileName = String(format:"PatientInfo%d.csv",counter)
let fileURL = path.appendingPathComponent(fileName)
try csvString.write(to: fileURL, atomically: true, encoding: .utf8)
And in the next iteration, increase the counter value by 1.