Search code examples
iosxcode5

Retrieve files from Dirrectory


My Application creates Png, Pdf, and Jpg files and stores in Documentary with different name formats. How can i retrieve all filetypes at a time. For example If i want to count how many number of pdf files in documentary, where all files exists and i have to count only pdf files. How can i achieve this for particular file types.

   NSFileManager *filemanage = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *filelist= [filemanage contentsOfDirectoryAtPath:[docPaths objectAtIndex:0] error:nil];

NSInteger filescount = [filelist count];
NSString *filesnumber = [NSString stringWithFormat:@"%d", filescount];
NSLog(@"filesnumber:%@", filesnumber);
fileLabel.text = filesnumber;

Solution

  • NSFileManager *filemanage = [NSFileManager defaultManager];
    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSArray *filelist= [filemanage contentsOfDirectoryAtPath:[docPaths objectAtIndex:0] error:nil];
    
    NSInteger filescount = 0;
    for (NSString *fileName in filelist) {
        if ([[fileName pathExtension] isEqualToString:@"pdf"]) {
            filescount++;
        }
    }
    
    NSString *filesnumber = [NSString stringWithFormat:@"%d", filescount];
    NSLog(@"filesnumber:%@", filesnumber);
    fileLabel.text = filesnumber;
    

    You could || the if statement to add .jpg, .png and whatever else you may want.