在 macOS 上打包 Avalonia 应用,核心是生成符合 Apple 生态规范的
.app包,并完成签名与公证(Gatekeeper 要求)。整个流程不依赖 Xcode 图形界面,主要靠
dotnetCLI +
Dotnet.Bundle工具链完成。
配置项目文件(.csproj)
这是打包前提,必须显式声明 macOS 专用属性:
添加Dotnet.Bundle包引用:
<packagereference include="Dotnet.Bundle" version="*"></packagereference>在
<propertygroup></propertygroup>中设置 Bundle 元信息(关键字段不能遗漏):
<cfbundlename>MyApp</cfbundlename>
<cfbundledisplayname>MyApp</cfbundledisplayname>
<cfbundleidentifier>com.example.myapp</cfbundleidentifier>
<cfbundleversion>1.0.0</cfbundleversion>
<cfbundleshortversionstring>1.0</cfbundleshortversionstring>
<cfbundlepackagetype>APPL</cfbundlepackagetype>
<cfbundleexecutable>MyApp</cfbundleexecutable>
<cfbundleiconfile>AppIcon.icns</cfbundleiconfile>
<nsprincipalclass>NSApplication</nsprincipalclass>
<nshighresolutioncapable>true</nshighresolutioncapable>确保
AppIcon.icns文件已放入项目根目录或
Resources/目录,并在
<itemgroup></itemgroup>中标记为
<bundleresource></bundleresource>或
<content></content>并设
CopyToOutputDirectory为
PreserveNewest
执行打包命令
在项目根目录终端中运行:
dotnet publish -c Release -r osx-x64 --self-contained true -p:PublishTrimmed=true -p:PublishSingleFile=false
注意:
–
-r osx-x64(Intel)或
-r osx-arm64(Apple Silicon)需按目标机器匹配;
–
PublishSingleFile=false是推荐选项,因 macOS Bundle 要求结构化目录(含
Contents/子目录),单文件模式不兼容;
– 输出路径默认为
bin/Release/net8.0/osx-x64/publish/,其中会生成
MyApp.app文件夹。
签名与公证(上架/分发必需)
未签名的 .app 在 macOS 10.15+ 无法启动(“已损坏”提示):
代码签名:使用 Apple 开发者证书(需加入 Apple Developer Program):codesign --force --deep --sign "Developer ID Application: Your Name (ABC123)" --options runtime MyApp.app公证(Notarization):上传到 Apple 服务验证安全策略:
xcrun notarytool submit MyApp.app --keychain-profile "AC_PASSWORD" --wait
(需提前配置
notarytool凭据) Stapling(钉住公证票证):
xcrun stapler staple MyApp.app
可选:制作 DMG 安装镜像
提升用户安装体验,可用脚本自动化生成带拖拽图标的 DMG:
准备背景图、应用图标、别名(指向 Applications) 使用hdiutil创建并配置:
hdiutil create -volname "MyApp" -srcfolder "MyApp.app" -ov -format UDZO MyApp.dmg更完整方案可参考 Avalonia 官方示例中的
bundle.sh脚本(支持自动检测芯片架构)
完成签名和 stapling 后,双击即可正常运行,且能通过 Gatekeeper 验证。整个流程无需 Visual Studio 或 Rider,纯命令行驱动,适合 CI/CD 集成。
