I am using this code to open a .csv file
func retrieveDataFromCSV() {
do {
var csvString:String = ""
if selectedCSVUrlFile != "" {
csvString = try String(contentsOf: URL(string: "file://\(selectedCSVUrlFile)")!, encoding: .utf8)
// csvString = try String(contentsOf: URL(string: "\(selectedCSVUrlFile)")!, encoding: .utf8)
} else {
}
let csv = try! CSVReader(string: csvString,
hasHeaderRow: true) // It must be true.
let headerRow = csv.headerRow!
print("\(headerRow)") // => ["id", "name"]
while let row = csv.next() {
valuesArrayFromCSV.append(Double(row[0]) ?? 0)
}
DisplayGraph()
} catch {
print(error)
}
}
it usually works but occasionally it wont be able to open the file, when this happens, it craashes with
Thread 1: Fatal error: unexpectedly found nil while unwrapping an Optional value
1. I dont know why sometimes it works and other is doesnt. the files that are being opened are identical in form and only differ in the value of the data. Maybe I dont have a permission set correctly somewhere?
2. How can I prevent crashing on when file access fails? as you can see it is already in a do,try,catch statement, I have tried adding a "If Let {} but could manage to get that to work.
Thanks in advance.