首页 > 解决方案 > macOS application file association

问题描述

I have been trying to sift through information for a while now, and I am having issues determining what is still still relevant. It also seems that for some reason there is less info on the subject than there should be.

I am working on an application that is distributed for macOS. I would like to associate a custom file extension with my application. I would like the user to be able to double click on one of the files and have the application open it. Its easy enough for me to pick the application to open the files, but I cant figure out how to get the filename for the opened file.

The only thing I have found so far is to create an application from an AppleScript. Then the AppleScript can parse the arguments and call the main application with them. I have two problems with this approach.

First, what happens if the user changes it and selects the application directly? I supposed it just wont work? Is there any way around that?

Second, how do I associate the application automatically in the first place? I found information about CFBundleTypeExtensions, but then later found that this was deprecated. I found some info on UTI's and Launch Services. It makes sense how to add a UTI to the plist file and run the lsregister command. How would you do this automatically though? The user installs the application using a dmg, at what point can I run the lsregister command?

标签: c++macosfile-associationdmg

解决方案


将类似以下内容添加到您的Info.plist. 它会告诉 macOS 你的应用程序句柄.foo.bar文件。

<key>CFBundleDocumentTypes</key>
<array>
<dict>
    <key>CFBundleTypeRole</key>
        <string>Viewer</string>
    <key>CFBundleTypeExtensions</key>
    <array>
        <string>foo</string>
        <string>bar</string>
    </array>
    <key>CFBundleTypeIconFile</key>
        <string>FileIcons.icns</string>
    <key>CFBundleTypeMIMETypes</key>
        <string>application/octet-stream</string>
    <key>CFBundleTypeName</key>
        <string>Something Unique Here</string>
    <key>CFBundleTypeOSTypes</key>
    <array>
        <string>****</string>
    </array>
</dict>
</array>

FileIcons.icns应该包含注册文件的图标文件。如果您不想创建文件图标,可以将该字符串留空:

<key>CFBundleTypeIconFile</key>
    <string></string>

CFBundleTypeMIMETypes设置为application/octet-stream以上。这是通用二进制数据的 MIME 类型。如果文件实际上具有正确的 MIME 类型,则使用这些类型。

一旦 macOS 看到您的应用程序(例如下载时),它会自动知道打开.foo.bar. 你不需要在外部运行任何东西。

最后,当用户双击一个.foo.bar文件时,macOS 将启动您的应用程序,并且它会收到一个“打开文件”事件。你需要处理它。你如何做到这一点取决于你使用什么框架/语言来开发你的应用程序。


推荐阅读