Fast iterative web folder to place filenames in an array
I want to put the filenames of the web folder "mywwwddress" into an array but println gives me an empty array: []
func files(){
var urls : [NSURL] = []
let dirUrl = NSURL(string: "mywwwadres")
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator? = fileManager.enumeratorAtURL(dirUrl!, includingPropertiesForKeys: nil, options: nil, errorHandler: nil)
while let url = enumerator?.nextObject() as! NSURL? {
urls.append(url)
}
println(urls)
}
+3
source to share
1 answer
When I try to execute the code with a directory url on the local filesystem it works fine for me, so you might want to add more errors to see if there is a problem with the url you are using.
Moreover, since the NSEnumerator
matches SequenceType
, instead you can use for...in
, or other transaction processing sequences, such as map
that may be slightly simplify the code.
Here's a buggy version to try:
func files() {
let fileManager = NSFileManager.defaultManager()
let url = NSURL(string: "mywwwadres")
assert(url != nil, "Invalid URL")
let enumerator = url.flatMap { fileManager.enumeratorAtURL($0,
includingPropertiesForKeys: nil,
options: nil)
{ url, error in
println("error with url \(url): \(error)")
return true // true to keep going
}
}
assert(enumerator != nil, "Failed to create enumerator")
let urls = enumerator.map { enumerator in
map(enumerator) { url in
url as! NSURL
}
}
println(urls ?? [])
}
0
source to share