Organize files in Xcode project and create folder list programmatically

I have the following structure inside my Xcode project in the resource navigator that I want to mirror inside my application.

enter image description here

Namely, I want to "scan" in the "Books" folder and get NSArray

all the folders in it. The next step I want to get NSArray

all files in each folder.

So far I've tried to use anything related NSBundle

to get the list of folders, but this is giving me wrong results:

NSLog(@"bundle path is %@", [[NSBundle mainBundle] bundlePath]);

NSLog(@"resource path is %@", [[NSBundle mainBundle] resourcePath]);

      

Both of these methods do not programmatically reflect the actual folder structure.

Can this be done?

+3


source to share


1 answer


As @rmaddy pointed out, you should have blue folders in your Xcode project and then use NSDirectoryEnumerator

to get a complete list of all folders.

This is how I solved it:



NSURL *bundleURL = [[[NSBundle mainBundle] bundleURL] URLByAppendingPathComponent:@"Books" isDirectory:YES];

NSDirectoryEnumerator *dirEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:bundleURL includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, NSURLIsDirectoryKey,nil] options:NSDirectoryEnumerationSkipsSubdirectoryDescendants  errorHandler:nil];

for (NSURL *theURL in dirEnumerator){

    // Retrieve the file name. From NSURLNameKey, cached during the enumeration.
    NSString *folderName;
    [theURL getResourceValue:&folderName forKey:NSURLNameKey error:NULL];

    // Retrieve whether a directory. From NSURLIsDirectoryKey cached during the enumeration.

    NSNumber *isDirectory;
    [theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];

    if([isDirectory boolValue] == YES){
        NSLog(@"Name of dir is %@", folderName);
    }
}

      

+4


source







All Articles