Here's a solution using -subpathsOfDirectoryAtPath:rootPath , with file URLs and modern bells and whistles.
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
... and the same in 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)) } }
mz2 Apr 10 '16 at 19:21 2016-04-10 19:21
source share