techno
techno

Reputation: 6500

Adding files to Array from Sub Folders

I'm using the following code to add files of a specific extension from a folder to an array.

self.fileArray = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil).filter{ filterExtensions.contains($0.pathExtension) }

I need to add files from all subfolders within the selected folder/Drive.

How can I achieve this?

Upvotes: 0

Views: 438

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236420

You can get url resource key isRegularFileKey to check if the enumerated url is a regular file. You can also set the options to skip hidden files and package descendants, otherwise it will also copy hidden files like .DS_Store:

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
var files: [URL] = []
FileManager.default.enumerator(at: documentsDirectory, includingPropertiesForKeys: [], options: [.skipsHiddenFiles, .skipsPackageDescendants])?.forEach {
    if let url = $0 as? URL, (try? url.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true {
        files.append(url)
    }
}

You can also get all objects returned from the enumerator and conditionally cast them into an array of URLs and then filter the URLs which meets the condition:

if let files = (FileManager.default.enumerator(at: documentsDirectory, includingPropertiesForKeys: [], options: [.skipsHiddenFiles, .skipsPackageDescendants])?.allObjects as? [URL])?
    .filter({
      (try? $0.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true
}) {
   print(files.count)
}

Upvotes: 1

Vini App
Vini App

Reputation: 7485

You can get like this :

let enumerator = try FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil)!.allObjects

self.fileArray = enumerator.filter { filterExtensions.contains(($0 as! URL).pathExtension) } as! [URL]

Upvotes: 1

Related Questions