Restrict access to certain folders using NSOpenPanel

こ雲淡風輕ζ 提交于 2019-12-07 05:23:27

问题


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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/5682666/restrict-access-to-certain-folders-using-nsopenpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!