Search code examples
swiftnsfilemanager

Get only url of files without directories


How can I get URL of the files in a URL?

I tried these:

directoryContents = try FileManager.default.contentsOfDirectory(at: aURL, includingPropertiesForKeys: [URLResourceKey.isRegularFileKey], options: [])

and

...contentsOfDirectory(at: aURL, includingPropertiesForKeys: nil, options: []).filter{ $0.isFileURL })

Both result is equal to

...contentsOfDirectory(at: aURL, includingPropertiesForKeys: nil, options: [])

that return the list of files and folders and it get the list without any filter and option.

Also I tried to get only directories by URLResourceKey.isDirectoryKey, but it didn't work.

How can I get the URL of files without directories?


Solution

  • includingPropertiesForKeys does retrieve the information for the specified keys from the url while traversing the directory for performance reasons, it's not a filter criterium.

    You have to filter the result explicitly either by the isDirectory value

    let directoryContents = try FileManager.default.contentsOfDirectory(at: aURL, includingPropertiesForKeys: [.isDirectoryKey])
    let filesOnly = directoryContents.filter { (url) -> Bool in
        do {
            let resourceValues = try url.resourceValues(forKeys: [.isDirectoryKey])
            return !resourceValues.isDirectory!
        } catch { return false }
    }
    
    print(filesOnly.count)
    

    Or in macOS 10.11+, iOS 9.0+ with hasDirectoryPath

    let directoryContents = try FileManager.default.contentsOfDirectory(at: aURL, includingPropertiesForKeys: nil)
    let filesOnly = directoryContents.filter { !$0.hasDirectoryPath }
    print(filesOnly.count)