1

According to How to find NSDocumentDirectory in swift? I wrote the next code:

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let files = NSFileManager().enumeratorAtPath(documentsPath)
var myString:String = "/"
while let file: AnyObject = files?.nextObject() {
    myString += (file as String + "/")
}
println(myString)

But, actually the problem is that, when I debug the program, documentsPath equals to (String) "", after executing NSSearchPathForDirectoriesInDomains command. Besides, I'm trying to do this not in MainViewController, I'm trying to execute this command in TableViewController.

enter image description here

However, it works in playground; It doesn't work for any project that I create

let docdir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String + "Test.txt"

returns the correct path, wtf?

Community
  • 1
  • 1
Olexiy Pyvovarov
  • 870
  • 2
  • 17
  • 32

1 Answers1

2

I looked in the documentation for NSSearchPathForDirectoriesInDomains and it says,

You should consider using the NSFileManager methods URLsForDirectory:inDomains: and URLForDirectory:inDomain:appropriateForURL:create:error:. which return URLs, which are the preferred format.

And the following works perfectly:

    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    println(urls[0])

That said, your code is failing because the items in the array returned by NSSearchPathForDirectoriesInDomains are not Strings. If you want to keep your original code, just change as String to as NSString

Daniel T.
  • 32,821
  • 6
  • 50
  • 72
  • This could be a bug in Apple's SDK. `NSSearchPathForDirectoriesInDomains` is returning an array of `NSPathStore2` objects, which can be cast into `NSStrings`, but not `Strings`. – Daniel T. Oct 19 '14 at 16:13