iOS 扫描文件夹及所有子文件夹下面的文件

若如初见. 提交于 2020-08-14 23:22:56
- (void)fileArrayWithFilePath:(NSString *)filePath {
    if ([self isDirectory:filePath]) {
        NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:nil];
        for (NSInteger i = 0; i < array.count; i ++) {
            if([self isDirectory:[filePath stringByAppendingPathComponent:array[i]]]) {
                [self.folderArray addObject:[filePath stringByAppendingPathComponent:array[i]]];
            } else {
                [self.fileArray addObject:[filePath stringByAppendingPathComponent:array[i]]];
            }
        }
        
        while (self.folderArray.count > 0) {
            NSString *firstObject = [self.folderArray firstObject];
            NSArray *arr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:firstObject error:nil];
            for (NSInteger i = 0; i < arr.count; i ++) {
                if([self isDirectory:[firstObject stringByAppendingPathComponent:arr[i]]]) {
                    [self.folderArray addObject:[firstObject stringByAppendingPathComponent:arr[i]]];
                } else {
                    [self.fileArray addObject:[firstObject stringByAppendingPathComponent:arr[i]]];
                }
            }
            
            [self.folderArray removeObject:firstObject];
        }
        
        for (NSInteger i = 0; i < self.fileArray.count ; i ++) {
            NSString *str = self.fileArray[i];
            [self.fileData addObject:[[str componentsSeparatedByString:@"/"] lastObject]];
        }
    } else {//文件
        [self.fileData addObject:[[filePath componentsSeparatedByString:@"/"] lastObject]];
    }
}
- (BOOL)isDirectory:(NSString *)filePath {
    BOOL isDirectory = NO;
    [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
    return isDirectory;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!