Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

In Swift you can limit particular types this way, by implementing shouldEnable url delegate method.


 func panel(_ sender: Any, shouldEnable url: URL) -> Bool {
        if String(url.pathExtension) == "pdf" {
            return false
        }
        return true
 }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top