简体   繁体   English

如何使用可可中的contentsOfDirectoryAtPath从文件夹中获取目录?

[英]How to get list of contents from folder using contentsOfDirectoryAtPath in cocoa?

I want to fetch all contents of the folder and add to a submenu of NSMenuItems. 我想获取文件夹的所有内容并添加到NSMenuItems的子菜单中。

For achieving this, I'm using code given below: 为了实现这一点,我使用下面给出的代码:

NSArray *dirContents = [[NSArray alloc]init];
dirContents=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:updated error:nil];

This code is working but only in one folder. 该代码有效,但仅在一个文件夹中。 Strange but it is true. 奇怪,但这是事实。 I have tried the same code for other folders but it gives nil value in dirContents . 我为其他文件夹尝试了相同的代码,但它在dirContents给出了nil值。

So how can I access the list of all the contents of a selected folder? 那么,如何访问所选文件夹的所有内容列表?

Try this to track the access error. 尝试此操作以跟踪访问错误。

NSError *error;
NSArray *dirContents = [[NSArray alloc]init];
dirContents=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:updated error:&error];

if(error){
    NSLog(@"%@",error);
}

Make sure you use relative path to the directory, if the app is sandboxed, not absolute path. 如果应用被沙箱化,请确保使用相对目录的路径,而不是绝对路径。

NSURL *containerUrl =[[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"Your.app.container.id"];
path = [[containerUrl URLByAppendingPathComponent:@"your/folder/path"] path];
+(NSArray*)allURLs:(NSURL*)url{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
    NSURL *bundleURL = url;
    NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:bundleURL
                                          includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]
                                                             options:NSDirectoryEnumerationSkipsHiddenFiles
                                                        errorHandler:^BOOL(NSURL *url, NSError *error)
                                         {
                                             NSLog(@"[Error] %@ (%@)", error, url);
                                             return url;
                                         }];

    NSMutableArray *mutableFileURLs = [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]) {
            [mutableFileURLs addObject:fileURL];
        }
    }


    return mutableFileURLs;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM