I'm making an app in swift 3.0.2 using XCode 8.2 and I am trying to recursively list the files that are shared with the iOS app through itunes.
At the moment, the following code works:
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
print(documentsUrl.absoluteString)
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
print(directoryContents)
} catch let error as NSError {
print(error.localizedDescription)
}
However, the documentation for contentsOfDirectory located here states that the function only performs a shallow traversal of the URL and suggests a function that does a deep traversal of the URL, namely enumerator, whose documentation is located here.
I am using the following snippet to try and list all files under the current URL using deep traversal:
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
print(documentsUrl.absoluteString)
let dirContents = FileManager.default.enumerator(at: documentsUrl.resolvingSymlinksInPath(), includingPropertiesForKeys: nil, options: [])
print(dirContents.debugDescription)
while let element = dirContents?.nextObject() as? String {
print(element)
}
The issue is that while the first snippet does display file URLs the second one does not display anything.
Could somebody please advise on what could I do to fix that? I would really like to use the second snippet rather than attempt a workaround using the first function.
FileManager
has two methods to obtain a directory enumerator:
enumerator(atPath path: String)
enumerator(at url: URL, ...)
The first one returns an enumerator which enumerates strings (the file paths), the second one returns an enumerator which enumerates URLs.
Your code uses the URL-based enumerator, therefore the conditional
casts to as? String
fail and no output is produced.
You have to cast to URL
instead:
if let dirContents = FileManager.default.enumerator(at: documentsUrl.resolvingSymlinksInPath(), includingPropertiesForKeys: nil) {
while let url = dirContents.nextObject() as? URL {
print(url.path)
}
}
You can also iterate with a for-loop:
if let dirContents = FileManager.default.enumerator(at: documentsUrl.resolvingSymlinksInPath(), includingPropertiesForKeys: nil) {
for case let url as URL in dirContents {
print(url.path)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With