user88975
user88975

Reputation: 1648

Allow only folders and files in NSOpenPanel

In my application I need to support folders and files selection. So far I have these settings

NSOpenPanel *openPanel = [[NSOpenPanel alloc] init];
[openPanel setAllowsMultipleSelection:YES];
[openPanel setCanChooseDirectories:YES];
[openPanel setCanCreateDirectories:NO];

But with this anyone can choose .app files(folders in reality). I see that there is an option for setting allowed file types which doesnt work here as I need a wildcard file selection and exclude only particular types.

Is there any way to exclude these files ?

Upvotes: 1

Views: 1015

Answers (1)

mahal tertin
mahal tertin

Reputation: 3416

Use - (BOOL)panel:(id)sender shouldEnableURL:(NSURL *)url of the NSOpenSavePanelDelegate. Inside this use NSURL to get the UTI and check it against your accepted types list. Full List of UTI-Types. You could also negate the logic to exclude the unsupported types, whichever is more appropriate to your app and what your users expect. If you can evaluate the file fast enough, you may even open it and then enable or disable it in the Panel.

- (BOOL)panel:(id)sender shouldEnableURL:(NSURL *)url
    NSString* itemUTI = nil;
    NSError* outErr = nil;
    BOOL showInPanel = NO;

    BOOL success = [url getResourceValue:&itemUTI NSURLTypeIdentifierKey error:&outErr];
    if ( ! success || nil == itemUTI) {
        // handle failure
    } else {
        showInPanel = UTTypeConformsTo(itemUTI, kUTTypeData) || UTTypeConformsTo(itemUTI, kUTTypeFolder);
    }

    return showInPanel;
}

Upvotes: 2

Related Questions