3

I am trying to get a list of files in document folder in Swift, here's a code snippet:

let fileManager = FileManager.default
if let dir = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
    print(dir.absoluteString)                // print 1

    do {
        let files = try fileManager.contentsOfDirectory(atPath: dir.absoluteString)
        print(files)                         // print 2
    } catch {
        print(error.localizedDescription)    // print 3
    }
}

Then "print 1" prints:

file:///Users/.../.../Documents/

And "print 3" prints:

The folder "Documents" doesn't exist.

Currently, there are quite a few files saved in that folder, at very least, my default.realm file is there. Why does this happen?

rmaddy
  • 298,130
  • 40
  • 468
  • 517
K.Wu
  • 2,903
  • 3
  • 24
  • 46
  • You don't want to use `absoluteString`. That doesn't return a properly formed file path. See Ali's answer below. – Duncan C Aug 20 '18 at 21:58

1 Answers1

9

You should use dir.path in order to convert the URL to a file path:

let files = try fileManager.contentsOfDirectory(atPath: dir.path)

rmaddy
  • 298,130
  • 40
  • 468
  • 517
Ali Moazenzadeh
  • 426
  • 2
  • 10
  • This is the correct answer. you could also use `contentsOfDirectory(at:includingPropertiesForKeys:options:)`, which takes a URL rather than a path string. – Duncan C Aug 20 '18 at 21:56