Listing All Files in a Folder Recursively with Swift

listing all files in a folder recursively with swift

FileManager has also a method for a deep search: enumerator(at:includingPropertiesForKeys:options:errorHandler:)

To get only the files you have to iterate the enumerator and filter the files

let url = URL(fileURLWithPath: "/path/to/directory")
var files = [URL]()
if let enumerator = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) {
for case let fileURL as URL in enumerator {
do {
let fileAttributes = try fileURL.resourceValues(forKeys:[.isRegularFileKey])
if fileAttributes.isRegularFile! {
files.append(fileURL)
}
} catch { print(error, fileURL) }
}
print(files)
}

It's highly recommended to use URLs rather than string paths.

How to Use Recursion to get all Files in a Directory Tree for Firebase Cloud Storage

As the Firebase documentation on listing all files shows, you can call listAll(completion:) on each prefix to recursively.

So:

for prefix in result.prefixes {
print(prefix.fullPath)
prefix.listAll(...) // List files in subdirectory
}

Iterate through files in a folder and its subfolders using Swift's FileManager

Use the nextObject() method of enumerator:

while let element = enumerator?.nextObject() as? String {
if element.hasSuffix("ext") { // checks the extension
}
}

How to list all folders and their subdirectories/files in iPhone SDK?

Take into account that your app runs in a sandbox and would not be able to get any folder/file outside of that sandbox.

ObjectiveC

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0];

NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
for (NSString *s in fileList){
NSLog(@"%@", s);
}

Swift 4

guard let documentsDirectory =  try? FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else { return }
guard let fileEnumerator = FileManager.default.enumerator(at: documentsDirectory, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions()) else { return }
while let file = fileEnumerator.nextObject() {
print(file)
}

How do I get all resource paths in my bundle recursively in iOS?

I got this working using the code posted by @rekle as a starting point. The trick is to use NSDirectoryEnumerator, which will do this recursively. Here's the function I wrote in case anyone needs it.

- (NSArray *)recursivePathsForResourcesOfType:(NSString *)type inDirectory:(NSString *)directoryPath{

NSMutableArray *filePaths = [[NSMutableArray alloc] init];

// Enumerators are recursive
NSDirectoryEnumerator *enumerator = [[[NSFileManager defaultManager] enumeratorAtPath:directoryPath] retain];

NSString *filePath;

while ((filePath = [enumerator nextObject]) != nil){

// If we have the right type of file, add it to the list
// Make sure to prepend the directory path
if([[filePath pathExtension] isEqualToString:type]){
[filePaths addObject:[directoryPath stringByAppendingPathComponent:filePath]];
}
}

[enumerator release];

return [filePaths autorelease];
}

Swift, using NSURL

func recursivePathsForResources(type type: String) -> [NSURL] {

// Enumerators are recursive
let enumerator = NSFileManager.defaultManager().enumeratorAtPath(bundlePath)
var filePaths = [NSURL]()

while let filePath = enumerator?.nextObject() as? String {

if NSURL(fileURLWithPath: filePath).pathExtension == type {
filePaths.append(bundleURL.URLByAppendingPathComponent(filePath))
}
}

return filePaths
}

Get Subdirectories using Swift

There is no need to use a deep enumeration. Just get contentsOfDirectoryAtURL and filter the urls returned which are directories.

Xcode 11.4• Swift 5.2

extension URL {
func subDirectories() throws -> [URL] {
// @available(macOS 10.11, iOS 9.0, *)
guard hasDirectoryPath else { return [] }
return try FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]).filter(\.hasDirectoryPath)
}
}

usage:

 do {
let documentsDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let url = documentsDirectory.appendingPathComponent("pictures", isDirectory: true)
if !FileManager.default.fileExists(atPath: url.path) {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false, attributes: nil)
}
let subDirs = try documentsDirectory.subDirectories()
print("sub directories", subDirs)
subDirs.forEach { print($0.lastPathComponent) }
} catch {
print(error)
}

Get all URLs for resources in sub-directory in Swift

Consider that the yellow folders Sample Image are virtual groups, not real folders (although Xcode creates real folders in the project directory). All files in the yellow folders are moved into the Resources directory in the bundle when the app is built.

Real folders in the bundle are Sample Image in the project navigator.



Related Topics



Leave a reply



Submit