0

I have an array

var items: [String] = []

I want to add each filename in documents folder to this array.

  var error = NSErrorPointer()
    let fldrs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
    if fldrs != nil {
        //???
    }

Any help appreciated

2
  • 1
    Look at the docs for NSFileManager. Commented Mar 26, 2015 at 3:13
  • does this question really deserve down vote ??? Commented Mar 26, 2015 at 16:26

1 Answer 1

1

As mentioned by rmaddy you can use NSFileManager to list the contents of a directory using the URLsForDirectory method to get an array of urls and you can use map to extract only the last path component of those URLs:

let documentsUrl =  NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL

var fileURLs:[NSURL] {
    return (NSFileManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles | .SkipsSubdirectoryDescendants | .SkipsPackageDescendants, error: nil) as [NSURL]).sorted{$0.lastPathComponent<$1.lastPathComponent}
}

var myFileNames = fileURLs.map{$0.lastPathComponent!}

println(myFileNames.description) // ["Shared Playground Data"]

"testing".writeToURL(documentsUrl.URLByAppendingPathComponent("test1.txt"), atomically: true, encoding: NSUTF8StringEncoding, error: nil)
"testing2".writeToURL(documentsUrl.URLByAppendingPathComponent("test2.txt"), atomically: true, encoding: NSUTF8StringEncoding, error: nil)

myFileNames = fileURLs.map{$0.lastPathComponent!}

println(myFileNames.description) // "[Shared Playground Data, test1.txt, test2.txt]"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.