Reputation: 10172
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
Upvotes: 0
Views: 1109
Reputation: 236420
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]"
Upvotes: 1