Search code examples
macoscocoadirectorynsopenpanel

How to limit writable directory selection in NSOpenPanel?


I want user to select a directory for files to save into. My simplest codes (ARC):

NSOpenPanel *panel = [NSOpenPanel openPanel];

[panel setCanChooseDirectories:YES];
[panel setCanChooseFiles:NO];
[panel setAllowsMultipleSelection:NO];

if (NSOKButton == [panel runModal]) 
    return [[panel URLs] objectAtIndex:0];
else
    return nil;

However, I want to ensure the returned path writeable so that I can save files into it. How should I modify my codes?


Solution

  • Implement the shouldEnableURL delegate method as follows:

    - (BOOL)panel:(id)sender shouldEnableURL:(NSURL *)url
    {
        return [[NSFileManager defaultManager] isWritableFileAtPath:[url path]];
    }
    

    This will render all non-writable paths as unselectable in the open panel. The object that acts as your panel delegate should conform to NSOpenSavePanelDelegate.
    Don't forget to set it via:

    [panel setDelegate:self];
    

    Detailed information about the NSOpenSavePanelDelegate protocol can be found in the docs.