我已创建了保存按钮,我想创建一个.csv文件来存储屏幕上的x,y和对象名称,因为我无法检查它,因为我无法访问其创建的文件
@IBAction func saveButton(_ sender: Any) {
let objectsName = stringObjectName.joined(separator: ",")
let coX = stringObjectX.joined(separator: ",")
let coY = stringObjectY.joined(separator: ",")
let fileName = getDocumentsDirectory().appendingPathComponent("output.csv")
CSVFilesName.append(fileName)
var csvText = "Name, Data X, Data Y\n"
let count = stringObjectName.count
if count > 0 {
for _ in 0..<(stringObjectName.count-1) {
let newLine = "\(objectsName),\(coX),\(coY)\n"
csvText.append(contentsOf: newLine)
}
}
do {
try csvText.write(to: fileName, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("error")
}
print(fileName)
}
之后我尝试访问文件调用“output.csv”,它假定存储在另一个视口的文档目录中。因此,我创建了方法,通过使用和存储CSVFile
将方法从另一个视图控制器传递到当前视图控制器 var CSVFileName = [URL]()
func assignArray() {
let cameraVC = CameraViewController()
CSVFileName = cameraVC.CSVFilesName
print(CSVFileName)
}
问题从这里开始,因为我有一个数组,假设在String
中存储文件名 let fileNames = ["sth1.csv", "sth2.csv"]
但我找不到将CSVFileName从保存按钮转换为String,并将“静态数组”替换为“动态数组”并更改下面的方法以获取 来自FileManager()。default.url而不是fileURL的URL,以显示和访问TableViewController数据
private func prepareFileURLS() {
for file in fileNames {
let fileParts = file.components(separatedBy: ".")
print(fileParts[0])
if let fileURL = Bundle.main.url(forResource: fileParts[0], withExtension: fileParts[1]) {
if FileManager.default.fileExists(atPath: fileURL.path) {
print(fileURL)
fileURLs.append(fileURL as NSURL)
}
}
}
print(fileURLs)
}
答案 0 :(得分:0)
以下是您阅读CSV文件的方式:
func filterMenuCsvData()
{
do {
// This solution assumes you've got the file in your bundle
if let path = Bundle.main.path(forResource: "products_category", ofType: "csv"){
// STORE CONTENT OF FILE IN VARIABLE
let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
var rows : [String] = []
var readData = [String]()
rows = data.components(separatedBy: "\n")
for data in 0..<rows.count - 1{
if data == 0 || rows[data].contains(""){
continue
}
readData = rows[data].components(separatedBy: ",")
Category.append(readData[0])
if readData[2] != ""{
Occassions.append(readData[2])
}
selectedOccassionsRadioButtonIndex = Array(repeating: false, count: Occassions.count)
selectedCategoryRadioButtonIndex = Array(repeating: false, count: Category.count)
}
}
} catch let err as NSError {
// do something with Error}
print(err)
}
}