Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to open file with associated application?

Tags:

swift

I like to open a .xls file with Excel on macOS. I only found examples for C# but not for Swift.

Bonus question: Is it possible to launch that file with Excel also, even if this file extension is not associated with Excel?

like image 936
PjotrC Avatar asked Jun 21 '16 23:06

PjotrC


1 Answers

There is NSWorkspace.sharedWorkspace().openURL(fileURL) or NSWorkspace.sharedWorkspace().openFile(fileURL.path!) in order to open files by their default application.

If you want to force Excel, you can use NSWorkspace.sharedWorkspace().openFile(fileURL.path!, withApplication: "Microsoft Excel").

If you prefer forcing Excel and using URL objects, then there's the excessive openURLs(_:withAppBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifiers)

Though it is not a big deal yet I am updating the syntax as per Swift 4.2 -

NSWorkspace.shared.openFile(fileURL!.path)
NSWorkspace.shared.openFile(fileURL!.path, withApplication: "Microsoft Excel")
NSWorkspace.shared.open([fileURL!], withAppBundleIdentifier: "com.microsoft.Excel", options: NSWorkspace.LaunchOptions.withErrorPresentation, additionalEventParamDescriptor: nil, launchIdentifiers: nil)

To get the Bundle Identifier of any app, use this command in your terminal

 osascript -e 'id of app "*app_name*"'
like image 146
Kevin Low Avatar answered Nov 08 '22 19:11

Kevin Low