swift4nsfilemanager

Get all the "*.xxx" files in the document directory in Swift 4


I'm looking over the NSFileManager.h dox in Swift 4 and it seems it changed since I last used it (for the better!).

I'm wondering if contentsOfDirectoryAtURL:includingPropertiesForKeys, url or enumeratorAtURL:includingPropertiesForKeys provides a way to enumerate over a specific type of file, in my case images?

I've looked at the many Swift 2 answers and they all suggest looping and examining the name, and I want to be sure they haven't "fixed" this and I'm simply confused by the API?


Solution

  • Just filter the returned URLs by pathExtension

    do {
        let docs = try FileManager.default.contentsOfDirectory(at: .documentsDirectory, includingPropertiesForKeys: nil, options:  .skipsHiddenFiles)
        let images = docs.filter{ $0.pathExtension == "xxx" }
        print(images)
    } catch {
        print(error)
    }