我有一个可以将用户输入信息导出到csv文件中的应用程序。我在代码中将文件名设置为PatientInfo。但是,当我收到新数据并再次单击保存时。旧的将被覆盖。如何自动创建一个名称可能为PatientInfo_01的新csv文件?甚至更好的是,让用户在单击“保存”按钮后键入文件名。
这是我的原始代码:
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")
}
}
答案 0 :(得分:0)
尝试一下:
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)
然后在下一次迭代中,将计数器值增加1。