Tuesday, April 12, 2011

Open a file from the Mac OSX GUI: NSOpenPanel

This is a quick snippet that presents how to show a dialog to choose a file in Mac OS X programming in Objective-C. We will use the NSOpenPanel class.

Our first step is to write an IBAction routine, to answer to the user input, and link it to the interface (using XCode).
-(IBAction) action_OpenFile: (id) sender
{
}
Then we can populate it instantiating the NSOpenPanel class:

NSOpenPanel* openPanel = [NSOpenPanel openPanel];

This instantiate the class using the autorelease feature, so you don’t have to release it. Now you can personalize it using the features you need. For example the lines allow the user to choose just one file and not the directories:
[openPanel setCanChooseFiles:YES];
[openPanel setCanChooseDirectories:NO];
[openPanel setAllowsMultipleSelection: NO];

But what about the file types?
You may want to allocate an array of NSString with the list of allowed file types, and assign it to the panel. The following lines limit the users to choose the text files (txt or doc):

NSArray *tarr = [NSArray arrayWithObjects:@"txt", @"doc", nil];
[openPanel setAllowedFileTypes:tarr ];

Now you can show the panel, check if the user pressed the OK button, and retrieve the url of the selected file:
if ( [openPanel runModal] == NSOKButton ){
fileUrl = [openPanel URL];
}

Other methods runModal* exist to show the panel, but most of them are declared deprecated in the last OSX versions.

Here the final code:

-(IBAction) action_OpenFile: (id) sender
{
NSOpenPanel* openPanel = [NSOpenPanel openPanel];
[openPanel setCanChooseFiles:YES];
[openPanel setCanChooseDirectories:NO];
[openPanel setAllowsMultipleSelection: NO];
NSArray *tarr = [NSArray arrayWithObjects:@"txt", @"doc", nil];
[openPanel setAllowedFileTypes:tarr ];
if ( [openPanel runModal] == NSOKButton )
{
fileUrl = [openPanel URL];
// ...
// Use the file
// ...
}
}

Emilio

No comments:

Post a Comment