Swift: How to open file with associated application?

前端 未结 1 1535
暗喜
暗喜 2021-02-10 02:59

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

1条回答
  •  长情又很酷
    2021-02-10 03:31

    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*"'
    

    0 讨论(0)
提交回复
热议问题