How to get all folders paths that contains music (mp3) in Cocoa?

こ雲淡風輕ζ 提交于 2019-12-07 14:04:34

Correct me if I am wrong. You want to get the number of mp3 in your folder, but while a folder only contains folders and mp3 files, the mp3-count is for its parent folder (and if the parent itself only contains folders and mp3s, it counts for its grand-parent, etc.) right ?

[manager enumeratorAtPath] is quite useful, but in this case it will certainly require you to maintain a stack to keep track of your browsed files.

Recursion is bliss, here.

- (BOOL)isMp3File:(NSString*)file
{
    return [file hasSuffix:@".mp3"];
}

- (BOOL)isHiddenFile:(NSString*)file
{
    return [file hasPrefix:@"."];
}

- (void)parseForMp3:(NSMutableDictionary*)dic
             inPath:(NSString*)currentPath
          forFolder:(NSString*)folder
{
    BOOL comboBreak = false;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError* error;
    NSArray* files = [fileManager contentsOfDirectoryAtPath:currentPath error:&error];
    if (error)
    {
        //throw error or anything
    }
    for (NSString *file in files)
    {
        BOOL isDirectory = false;
        NSString *fullPath = [NSString stringWithFormat:@"%@/%@", currentPath, file];
        [fileManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
        comboBreak = comboBreak || (!isDirectory &&
                                    ![self isMp3File:file] &&
                                    ![self isHiddenFile:file]);
        if (comboBreak)
            break;
    }
    for (NSString *file in files)
    {
        BOOL isDirectory = false;
        NSString *fullPath = [NSString stringWithFormat:@"%@/%@", currentPath, file];
        [fileManager fileExistsAtPath:fullPath isDirectory:&isDirectory];
        if (isDirectory)
        {
            if (!comboBreak)
            {
                [self parseForMp3:dic inPath:fullPath forFolder:folder];
            }
            else
            {
                [self parseForMp3:dic inPath:fullPath forFolder:fullPath];
            }
        }
        else if ([self isMp3File:file])
        {
            NSNumber *oldValue = [dic valueForKey:folder];
            oldValue = [NSNumber numberWithUnsignedInteger:[oldValue unsignedIntegerValue] + 1];
            [dic setValue:oldValue forKey:folder];
        }
    }
}


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [self parseForMp3:dic inPath:@"/Users/panosbaroudjian" forFolder:@"/Users/panosbaroudjian"];
    NSLog(@"%@", dic);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!