cocoa - 如何让非沙盒 macOS 应用程序在登录时启动?

cocoa - how to make a non-sandbox macOS app start at login?

我正在开发一个不会在 App Store 中发布的非沙盒 macOS 应用程序,我想在用户登录时将应用程序设置为 运行。

目前我找到的方法是使用Service Management framework和一个helper app,需要对这个app进行签名。以前有效的方法是LSSharedFileList,但是这个方法在macOS 10.14中不起作用。

有没有办法让这个简单的应用程序在登录时启动?

您可以将 launched 到 运行 的任何应用程序注册为用户代理。

在此示例中,只要用户登录,就会启动一个名为 On Startup 的应用程序。

第 1 步

您需要创建一个 "launchd.plist" 文件来描述该服务。在此示例中,您创建了一个名为 com.yourdomain.onstartup.plist 的文件,其中包含以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.yourdomain.onstartup</string>
    <key>LimitLoadToSessionType</key>
    <string>Aqua</string>
    <key>Program</key>
    <string>/Applications/On Startup.app/Contents/MacOS/On Startup</string>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

关键点是 RunAtLoad 属性 告诉 launchd 在用户会话加载时启动进程。

(注意:您可以通过构建字典并将其写为 属性 列表来创建此文件。)

第 2 步:

~/Library/LaunchAgents 中安装该文件。这是 launchd 查找 per-user launchd 配置文件的地方。

第 3 步:

执行命令

launchctl bootstrap ~/Library/LaunchAgents/com.yourdomain.onstartup.plist

或者等到系统重新启动。

bootstrap 命令告诉 launchd 要立即注册并激活一个新服务,但是 LaunchAgents 中的所有文件将在用户下次登录时自动注册。

如果您需要您的应用始终 运行,请考虑添加 KeepAlive 属性。还有大约十亿种其他选择。

第 4 步:

要阻止您的应用在登录时再次启动,请删除 com.yourdomain.onstartup.plist 文件。

如果您设置了 KeepAlive 属性,您还需要调用 launchctl bootout gui/501/com.yourdomain.onstartup 命令来停止服务并立即取消注册。 (注意:这会终止您的应用程序。)

man launchd.plist

man launchctl

macOS Daemons and Services