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 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 in the project navigator.
Related Topics
How to Calculate the 21! (21 Factorial) in Swift
How to Change Navigation Bar & Back Button Colour iOS 15
Swiftui - Wait Until Firestore Getdocuments() Is Finished Before Moving On
Declaration Is Only Valid at File Scope (Extension)
Why How to Use Codable with a Project Language Version of Swift 3.3
Select Multiple Rows in Tableview and Tick the Selected Ones
How to Completely Remove Realm Database from iOS
Differencebetween Type Safety and Type Inference
How to Create a Window with Transparent Background with Swift on Osx
Converting Swift Array to Cfarray in Xcode 8 (Swift 3)
What's the Difference Between Using or Not Using the 'Where' Clause with Generics
Curl Through Nstask Not Terminating If a Pipe Is Present
Select Filtered Search Results
How to Convert Between Related Types Through a Common Initializer
Child View Controller to Rotate While Parent View Controller Does Not