You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift开发macOS应用调用setDefaultApplication时遇权限错误

macOS Swift应用设置为.mp4默认打开应用的解决方案

问题核心

调用setDefaultApplication(at:toOpen:completion:)出现权限错误(Code=-54 permErr),是因为该API需要修改系统Launch Services数据库,仅开启全磁盘访问权限不足以获取这个系统级权限。

正确实现步骤

1. 在Info.plist中声明文档类型关联

先给应用添加对.mp4(UTI标识为public.mpeg-4)的支持,确保系统能识别你的应用处理该类型文件:

<key>CFBundleDocumentTypes</key>
<array>
    <dict>
        <key>CFBundleTypeName</key>
        <string>MPEG-4 Video</string>
        <key>CFBundleTypeRole</key>
        <string>Viewer</string> <!-- 或Editor,根据应用功能选择 -->
        <key>LSHandlerRank</key>
        <string>Default</string> <!-- 声明希望成为默认应用 -->
        <key>LSItemContentTypes</key>
        <array>
            <string>public.mpeg-4</string>
        </array>
    </dict>
</array>

2. 用lsregister刷新应用注册

通过系统自带的lsregister工具刷新应用的Launch Services注册,确保系统识别到应用的文档关联配置,再尝试设置默认应用:

let bundlePath = Bundle.main.bundlePath
let task = Process()
task.executableURL = URL(fileURLWithPath: "/usr/bin/lsregister")
task.arguments = ["-f", bundlePath]

do {
    try task.run()
    task.waitUntilExit()
    
    // 尝试设置默认应用
    NSWorkspace.shared.setDefaultApplication(at: Bundle.main.bundleURL, toOpen: .mpeg4Movie) { error in
        if let err = error {
            print("设置失败:\(err.localizedDescription)")
        } else {
            print("默认应用设置完成")
        }
    }
} catch {
    print("刷新注册失败:\(error.localizedDescription)")
}

3. 备选方案:引导用户手动设置

如果代码层面仍无法绕过权限限制,最可靠的方式是引导用户手动操作:

  • 右键点击任意.mp4文件 > 选择「显示简介」> 在「打开方式」中选择你的应用 > 点击「全部更改」按钮

关键说明

  • setDefaultApplication(at:toOpenFileAt:completion:)仅修改单个文件的打开关联,不会影响全局.mp4文件的默认设置。
  • 应用必须经过代码签名(Xcode调试签名或开发者ID签名),否则系统会限制其修改默认应用的权限。

内容的提问来源于stack exchange,提问作者wakame

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:52:40