0

I have a button in an app that when clicked should cause a dialog box to open. The user then chooses a folder, clicks OK, and then the app displays the number of PDF files in that folder.

I have the following code implemented below. How do I scan a folder for the amount of PDF files in it?

- (IBAction)selectPathButton:(NSButton *)sender {

    // Loop counter.
    int i;

    // Create a File Open Dialog class.
    NSOpenPanel* openDlg = [NSOpenPanel openPanel];

    // Set array of file types
    NSArray *fileTypesArray;
    fileTypesArray = [NSArray arrayWithObjects:@"pdf", nil];

    // Enable options in the dialog.
    [openDlg setCanChooseFiles:YES];
    [openDlg setAllowedFileTypes:fileTypesArray];
    [openDlg setAllowsMultipleSelection:TRUE];

    // Display the dialog box.  If the OK pressed,
    // process the files.
    if ( [openDlg runModal] == NSOKButton ) {

        // Gets list of all files selected
        NSArray *files = [openDlg URLs];

        // Loop through the files and process them.
        for( i = 0; i < [files count]; i++ ) {            
        }

        NSInteger payCount = [files count];
        self.payStubCountLabel.stringValue = [NSString stringWithFormat:@"%ld", (long)payCount];
    }
}
Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131
Green Developer
  • 187
  • 4
  • 18
  • 2
    Your code so far doesn't quite match the question. If you want the user to choose a folder, then set `[openDlg setCanChooseDirectories: YES]` and `[openDlg setCanChooseFiles: NO]`. Or is it that you want the user to multiple-select the PDF files? (Because that's what you have now.) – Smilin Brian Feb 21 '13 at 21:55
  • I want the user to select a folder and then it will count the number of pdf files in the selected folder. The code shown above was copy/pasted from another forum post. – Green Developer Feb 25 '13 at 16:23

1 Answers1

1

get files and directories under path

[NSFileManager]- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error;

get files and directories under path and subpath

[NSFileManager]- (NSArray *)subpathsOfDirectoryAtPath:(NSString *)path error:(NSError **)error;

then filter out pdf files.

NSMutableArray *pdfFiles = [NSMutableArray array];
for(NSString *fileName in files) {
    NSString *fileExt = [fileName pathExtension];
    if([fileExt compare:@"pdf" options:NSCaseInsensitiveSearch] == NSOrderSame) {
        [pdfFiles addObject:fileName];
    }
}

now what you want is in pdfFiles.

NSUInteger pdfFilesCount = [pdfFiles count];

if you only want count of pdf files, just using a variable with forin loop.

YuDenzel
  • 413
  • 3
  • 16