Catching arguments for creating a new document with a document-based application on MAC

277 views Asked by At

I am working on a document-based application for Mac. This application has its own data model and methods for writing and reading such kind of document. If I want to start this application with a predefined document I can do it in the following way: open the command line and type in

open -a /Applications/MyApp.app file

This only works if the argument "file" is a type of MyApp Document. Now I would like to execute MyApp with another kind of document (like a text file or something else). For example:

open -a /Applications/MyApp.app text.rtf

The delivered/committed text file should be read and inserted automatically into a complete new document from MyApp. Now I try to catch the text.rtf inside the int main(int argc, char *argv[]). But I get the following warning :

The document text.rtf could not be opened. MyApp cannot open files of this type

Does somebody has an idea how to catch the argument and import it as a part of a complete new MyApp-based document? How can I send it to the NSApplication?

Will be glad of any help.

2

There are 2 answers

3
Anya Shenanigans On BEST ANSWER

The files that are passed on the command line only apply if you open the application directly, such as how Paul R mentions.

Cocoa launches applications a little but unusually, what happens is the binary is executed, and you are asked to handle the documents that are passed in in a message. This means that they don't get passed onto you in the argv array.

If you want to properly handle accepting all file types, you need to add an openFiles handler to your app delegate such as:

-(void)application:(NSApplication *)sender openFiles:(NSArray *)filenames {
    for (NSString *file in filenames) {
        NSLog(@"%@", file);
    }
    [NSApp replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
}

This will accept any files, even those you're not registered to accept. You can sniff the file content and display the revelant message as part of the openFiles handler.

The openFiles handler works for both document and non-document based applications.

0
Paul R On

I think you can work around this by not using open and instead launching the application directly, e.g.

/Applications/MyApp.app/Contents/MacOS/MyApp text.rtf

This should at least give you argv[1] = "text.rtf".