指定文件路径下的所有层级的文件,包括子文件夹下的文件

时间:2021-04-26 09:55:25


 
+ (NSArray *)getFilesWithFilePath:(NSString *)filePath
{
    if ([self isFileExists:filePath])
    {
        // NSURL *urlFile = [[NSBundle mainBundle] bundleURL];
        NSURL *urlFile = [NSURL fileURLWithPath:filePath];
        NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtURL:urlFile
                                              includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]
                                                                 options:NSDirectoryEnumerationSkipsHiddenFiles
                                                            errorHandler:^BOOL(NSURL *url, NSError *error){
                                                                if (error)
                                                                {
                                                                    return NO;
                                                                }
                                                                
                                                                return YES;
                                                            }];
        
        NSMutableArray *array = [NSMutableArray array];
        for (NSURL *fileURL in enumerator)
        {
            NSString *filename;
            [fileURL getResourceValue:&filename forKey:NSURLNameKey error:nil];
            
            NSNumber *isDirectory;
            [fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];
            
            // Skip directories with '_' prefix, for example
            if ([filename hasPrefix:@"_"] && [isDirectory boolValue])
            {
                [enumerator skipDescendants];
                continue;
            }
            
            if (!isDirectory.boolValue)
            {
                // 转成文件路径
                [array addObject:fileURL.path];
            }
        }
        return array;
    }
    return nil;
}