rick
rick

Reputation: 1057

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?

Upvotes: 5

Views: 2709

Answers (2)

JGS
JGS

Reputation: 99

I consider:

var urls = try! FileManager.default.contentsOfDirectory(at: localDocumentsURL, includingPropertiesForKeys: nil, options: [])
urls = urls.filter { $0.isFileURL }

a good enough solution for iOS, in cases, where the app controls what is stored in the app-related sandbox-directories.

Upvotes: -1

vadian
vadian

Reputation: 285059

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)

Upvotes: 15

Related Questions