Aquí es una solución utilizando -subpathsOfDirectoryAtPath:rootPath
, con direcciones URL de archivos y modernas campanas nulabilidad Objective-C & silbatos.
typedef void (^FileEnumerationBlock)(NSURL *_Nonnull fileURL);
@interface NSFileManager (Extensions)
- (void)enumerateWithRootDirectoryURL:(nonnull NSURL *)rootURL
fileHandler:(FileEnumerationBlock _Nonnull)fileHandler
error:(NSError *_Nullable *_Nullable)error;
@end
@implementation NSFileManager (Extensions)
- (void)enumerateWithRootDirectoryURL:(NSURL *)rootURL
fileHandler:(FileEnumerationBlock)fileHandler
error:(NSError **)error {
NSString *rootPath = rootURL.path;
NSAssert(rootPath != nil, @"Invalid root URL %@ (nil path)", rootURL);
NSArray *subs = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:rootPath
error:error];
if (!subs) {
return;
}
for (NSString *sub in subs) {
fileHandler([rootURL URLByAppendingPathComponent:sub]);
}
}
@end
... y lo mismo en Swift:
func enumerate(rootDirectoryURL rootURL: NSURL, fileHandler:(URL:NSURL)->Void) throws {
guard let rootPath = rootURL.path else {
preconditionFailure("Invalid root URL: \(rootURL)")
}
let subs = try NSFileManager.defaultManager().subpathsOfDirectoryAtPath(rootPath)
for sub in subs {
fileHandler(URL: rootURL.URLByAppendingPathComponent(sub))
}
}
Función recursiva que se llama a sí misma para cada carpeta y busca el archivo – Guidhouse