Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the list of directores in NSDocumentDirectory?

I have created some directories in NSDocumentDirectory as

if (![tbxCreateFolder.text isEqualToString:@""]) {
NSArray  *arrPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryStr = [arrPaths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectoryStr stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",tbxCreateFolder.text]];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){

    NSError* error;
    if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]){

        NSLog(@"success");
        //Perfrom DB Insertation
    }
    else
    {
        NSLog(@"[%@] ERROR: attempting to write create MyFolder directory", [self class]);
        NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
    }
}

}

Now i want to get the list of directories that i have created in document folder but response is

NSArray *arrPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePathString = ([arrPaths count] > 0) ? [arrPaths objectAtIndex:0] : nil;
NSLog(@"dirContents %@",basePathString);

Response is:

/Users/amir/Library/Application Support/iPhone Simulator/6.1/Applications/7003E8D5-CCBB-4E54-896B-F4BD2F4D2CB1/Documents
like image 861
Amir iDev Avatar asked Feb 18 '13 07:02

Amir iDev


2 Answers

Here is the code:

NSString *documentDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// create directory named "test"
[[NSFileManager defaultManager] createDirectoryAtPath:[documentDirPath stringByAppendingPathComponent:@"test"] withIntermediateDirectories:YES attributes:nil error:nil];
// retrieved all directories
NSLog(@"%@", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirPath error:nil]);

 NSArray *paths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirPath error:nil];
 BOOL isDir = NO;
 for (NSString *path in paths) {
     if ([fileManager fileExistsAtPath:path isDirectory:&isDir] && isDir) {
         // path is directory
     }
}
like image 142
SAPLogix Avatar answered Nov 05 '22 18:11

SAPLogix


You could always enumerate the contents of the top level directory using -fileExistsAtPath:isDirectory: like this:

NSFileManager *sharedFileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *files = [sharedFileManager enumeratorAtPath:yourPath];

for (NSString *path in files) {
    BOOL isDirectory = NO;
    [sharedFileManager fileExistsAtPath:path isDirectory:&isDirectory];
    if (isDirectory) {
        // you found a directory, so do what you will with it
    }
}
like image 3
Caleb Avatar answered Nov 05 '22 18:11

Caleb