error opening .csv file

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.

Accepted Reply

OK, the problem was the presence of space " " in the file name. I am not certain why this is not permitted but my work around is to replace " " with "_" in my file names

Replies

OK, the problem was the presence of space " " in the file name. I am not certain why this is not permitted but my work around is to replace " " with "_" in my file names

Creating a file URL in this way is not recommended.

URL(string: "file://\(selectedCSVUrlFile)")!

You would experience some more issues when working with file paths with special characters.


Use this instead.

URL(fileURLWithPath: selectedCSVUrlFile)!

Try and see if you need to replace " " to "_".