Hi, I have been following a YouTube tutorial in enabling me to save a record to a csv file and I keep on getting the error Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) and Thread 1: Fatal error: Index out of range. I am not sure why this is the case, I would really appreciate the help!
Thanks
My code:
@IBAction func btnCSV(_ sender: Any) {
// File name
let sFileName = "test.csv"
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
// Try change this to put url to onedrive
let documentURL = URL(fileURLWithPath: documentDirectoryPath).appendingPathComponent(sFileName)
let output = OutputStream.toMemory()
let csvWriter = CHCSVWriter(outputStream: output, encoding: String.Encoding.utf8.rawValue, delimiter: ",".utf16.first!)
// Header for CSV file watch at 6:47 on video to find how to get from data base to change this
csvWriter?.writeField("Employee_ID")
csvWriter?.writeField("Employee_Name")
csvWriter?.writeField("Employee_Age")
csvWriter?.writeField("Employee_Designation")
csvWriter?.finishLine()
// Array to add data for the employee
var arrayofEmployeeData = [[String]]()
arrayofEmployeeData.append(["123,Joe,18,developer"])
arrayofEmployeeData.append(["223,John,29,engineer"])
arrayofEmployeeData.append(["545,David,30,CEO"])
// enumerated used for when there is mutliple data on one line
for(elements) in arrayofEmployeeData.enumerated(){
// Adds Employee ID
csvWriter?.writeField(elements.element[0])
// Adds Employee Name
csvWriter?.writeField(elements.element[1])
// Adds Employee Age
csvWriter?.writeField(elements.element[2])
// Adds Employee Designtion
csvWriter?.writeField(elements.element[3])
// Ends record and enables new record to be added
csvWriter?.finishLine()
}
csvWriter?.closeStream()
let buffer = (output.property(forKey: .dataWrittenToMemoryStreamKey)as? Data)!
do{
try buffer.write(to: documentURL)
}
catch{
}
}
}