Search code examples
swiftdirectorynsdocumentdirectory

Detect only folders & not files in Document Directory iOS Swift


I am trying to list only the folders that are present in my app's Document Directory and not the other files such as Images,videos,etc.

let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
    do
    {
        let files = try FileManager.default.contentsOfDirectory(atPath: documentDirectoryPath!)
        filesNames = files
       // print(files)
    } catch
    {
        print(error)
    }

I've tried the above code but it displays all of the contents from the document directory including other files! Is there any other way to filter out only folders and extracting the files

Please Help me out.


Solution

  • let fileManager = FileManager.default
    var dirPaths = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
    let docDir = dirPaths[0]
    
    do {
        let directoryContents = try FileManager.default.contentsOfDirectory(at: docDir, includingPropertiesForKeys: nil, options: [])
    
        let subDirs = directoryContents.filter{ $0.hasDirectoryPath }
        let subDirsName = subdirs.map{ $0.lastPathComponent }
    
        print(subDirsName)
    } catch let error as NSError {
        print(error)
    }