Opening files and URLs in default applications in OS X

After my article on Special Folders, a few people asked how to open a file in the default application.

For example, if I open a JPEG, whichever application is registered as the default app for JPEGs will execute. This is roughly analogous to ShellExecute in Windows.

The question was also asked about opening a URL in the default browser and also sending an email with the default mail application. These are closely related so I’ll cover them at the same time.

It’s actually pretty easy. I’ve got a TOpenDialog on a form, and the following code in a TButton.OnClick event:

Once we have the filename from the TOpenDialog, we create a NSWorkspace reference and use the openFile method, converting the filename string to a NSString on the way. NSWorkspace is defined in Macapi.Appkit and the NSSTR function to convert a String to a NSString is defined in Macapi.Foundation;

Opening a URL in a browser is slightly longer but not much:

Instead of the NSWorkspace.openFile method, we need to use openURL. This expects a NSURL as a parameter, so we construct that and load it up with the initWithString method, again converting our String to a NSString along the way. Executing that code causes Safari (on my machine) to open my website.

Opening a new mail and setting the To, Subject and Body is much the same, just down to the string we pass into our NSURL:

You can download the sample project from my delphi-samples repository on github.

One Comment

  • Hi, I was using this code to open a URL in the default web browser:
        AnsiString Command = “open http://www.malcolmgroves.com“;
        system(Command.c_str());
     
    Your code looks more robust.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">