6

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?

K.Wu
  • 3,553
  • 6
  • 31
  • 55
  • 1
    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

14

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

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ali Moazenzadeh
  • 584
  • 4
  • 13
  • 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