objective-ccocoamacosrestrictionnsopenpanel

Restrict access to certain folders using NSOpenPanel


I'm using NSOpenPanel to allow a user to select a folder to save documents into. I would like to restrict what folder (in terms of hierarchy) they can save into. Essentially, I want to prevent them from choosing any folder above:

/Users/username/

So the folder

/Users/username/cats/

would be acceptable but

/Users/username/

/Applications/cats/

would not be allowed. I was wondering how to implement this restriction.

Thanks.


Solution

  • Note that NSOpenPanel inherits from NSSavePanel, which in turn defines a delegate and a corresponding delegate protocol NSOpenSavePanelDelegate. You can use the delegate to extend the behaviour of the open panel so as to include the restriction you’ve listed in your question.

    For instance, assuming the application delegate implements the open panel restriction, make it conform to the NSOpenSavePanelDelegate protocol:

    @interface AppDelegate : NSObject <NSApplicationDelegate, NSOpenSavePanelDelegate>
    @end
    

    In the implementation of your application delegate, tell the open panel that the application delegate acts as the open panel delegate:

    NSOpenPanel *openPanel = [NSOpenPanel openPanel];
    [openPanel setDirectory:NSHomeDirectory()];
    [openPanel setCanChooseDirectories:NO];
    [openPanel setDelegate:self];
    [openPanel runModal];
    

    And implement the following delegate methods:

    - (BOOL)panel:(id)sender shouldEnableURL:(NSURL *)url {
        NSString *path = [url path];
        NSString *homeDir = NSHomeDirectory();
    
        return [path hasPrefix:homeDir] && ! [path isEqualToString:homeDir];
    }
    
    - (void)panel:(id)sender didChangeToDirectoryURL:(NSURL *)url {
        NSString *path = [url path];
        NSString *homeDir = NSHomeDirectory();
    
        // If the user has changed to a non home directory, send him back home!
        if (! [path hasPrefix:homeDir]) [sender setDirectory:homeDir];
    }
    
    - (BOOL)panel:(id)sender validateURL:(NSURL *)url error:(NSError **)outError {
        NSString *path = [url path];
        NSString *homeDir = NSHomeDirectory();
    
        if (![path hasPrefix:homeDir]) {
            if (outError)
               *outError = ; // create an appropriate NSError instance
    
            return NO;    
        }
        return YES;
    }