如何在 LSSharedFileListInsertItemURL 被弃用时从 macOS 10.11 开始添加 LoginItems?

How to add LoginItems since macOS 10.11 when LSSharedFileListInsertItemURL is deprecated?

如何在 macOS Mojave 上添加登录项?

我找到的解决方案:

macOS Swift: How to properly add application as Login Item

但自 macOS 10.11 起已弃用名为 LSSharedFileListInsertItemURL 的函数(但仍适用于 Mojave)。

使用时,XCode提示:

'kLSSharedFileListSessionLoginItems' is deprecated: first deprecated in macOS 10.11 - Use a LaunchAgent, XPCService or the ServiceManagement APIs instead.

根据该说明,我查看了 ServiceManagement。文件 SMLoginItem.h 定义 SMLoginItemSetEnabled 并且文档 https://developer.apple.com/documentation/servicemanagement/1501557-smloginitemsetenabled

Enable a helper application located in the main application bundle’s Contents/Library/LoginItems directory.

这不适用于我的情况,因为我想维护不在我的应用程序包中的应用程序的登录项,例如我想添加 /Applications/Books.app 作为登录项。

CFStringRef thePath = (__bridge CFStringRef)@"/Applications/Books.app";
return SMLoginItemSetEnabled(thePath, YES);

以上截取的代码returns

Could not locate login item /Applications/Books.app in the caller's bundle

Could not enable login item: /Applications/Books.app: 107: Malformed bundle

其次,如何以编程方式从系统中删除 LoginItem?

我不是为 AppleStore 创建应用程序,因此它不是沙盒(我已阅读 kLSSharedFileListSessionLoginItems is deprecated for sandboxed apps)

我在 App Store 和外部都有应用程序。我正在使用每种方法来根据分发方式添加登录项。目前没有其他方法可以管理它。

SMLoginItemSetEnabled 仅适用于您自己的应用程序包内的代理。对于 App Store 以外的应用,您可以使用 LSSharedFileListInsertItemURL。它已被弃用,但没有足够的替代品,它在 macOS 10.15 Beta SDK 中仍然可用。留意明年的进一步 API 变化。