aaHaa
aaHaa

Reputation: 43

String(contentsOf: URL) returns "No such file or directory"

I am a swift beginner and I am trying to write a function that reads the contents of a *.csv file and return a 2-D array [[Double]].

I am using Xcode 10.1 running on macOS 10.14.

I am using the following code (in a playground) to read the contents of the file into a String:

let home = FileManager.default.homeDirectoryForCurrentUser // 

let file = "Documents⁩/MyAppName⁩/x.csv"

let url = home.appendingPathComponent(file)

url.path // This gives: "/Users/userName/Documents⁩/MyAppName⁩/x.csv"

let s = try String(contentsOf: url)

I get the following error:

Error Domain=NSCocoaErrorDomain Code=260 "The file “x.csv” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/userName/Documents⁩/MyAppName⁩/x.csv, NSUnderlyingError=0x7febf3c991b0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

I know this is probably something ridiculously simple I am forgetting but I looked a lot for a solution and I couldn't find one. Any suggestions?

Upvotes: 4

Views: 1488

Answers (1)

rmaddy
rmaddy

Reputation: 318854

The issue is with this line:

let file = "Documents⁩/MyAppName⁩/x.csv"

You can't see it but between the s and / there is a hidden character - U+2069 - "POP DIRECTIONAL ISOLATE". Retype that line again without any special characters and your code will work.

That aside, here is how you should create the URL to the Documents folder.

let home = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

let file = "MyAppName⁩/x.csv"

Upvotes: 2

Related Questions