0

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?

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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)
}

12 Comments

The URL will always be a directory URL .. since I only allow directory selection in NSOpenPanel.
A different question .... My application is taking up 18GB of memory when processing large number of images...Should I explicitly dispose off NSImages?
Actually you have forgotten the the filter.
Filter for what? Do you need to add all files or just a specific file type?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.