Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-08-04

Opening a file in the browser from an OSX-Application

After the holidays lets start off with something simple: opening a file from your application in a browser. For iOS this can simply be done through the sharedApplication.openURL, but this call is not available under OS-X.

In OS-X it has to be done through the NSWorkspace. Otherwise it is almost identical to the method used for iOS:

NSWorkspace.shared().openFile(fileLogPath, withApplication: "Safari")

Note that this is not the same as in iOS. Here we have to specify explicitly in which application the file has to be openend. Where in iOS we can simply request to open a URL. It is possible to skip the "withApplication:" parameter in OS-X as well, but then the default app will be used for the extension of the file. Which can be irksome if for example the file in question is an XML file that we want to show in the browser, but would open in an XML editor (like XCode). Also keep in mind tat the user might want a different default browser than Safari, hence it would make sense to keep the "withApplication:" parameter configurable.

If we only want to open an URL in a browser, the syntax can in fact be a little easier:

        let url = URL(string: "http://www.balancingrock.nl")!
        NSWorkspace.shared().open(helpUrl)


Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.