Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileManager.default.enumerator does not return any files

Tags:

ios

swift

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.

like image 840
user2565010 Avatar asked Sep 12 '25 06:09

user2565010


1 Answers

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)
    }
}
like image 77
Martin R Avatar answered Sep 14 '25 21:09

Martin R