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

macOS 13 Ventura:应用内如何识别自身是否为登录启动项?

判断macOS应用是否为登录启动项的方法

以下是两种无需开发完整「登录时启动」控制功能的方案,可直接在应用内判断自身是否被添加为登录启动项:

方法一:读取系统登录项配置文件

macOS 中用户手动添加的登录项(包括系统设置「通用」里的登录项)会存储在 ~/Library/Preferences/com.apple.loginitems.plist 文件中。你可以读取该文件并检查自身是否在列表内:

Swift 示例代码

import Foundation

func isInLoginItems() -> Bool {
    let plistPath = NSHomeDirectory() + "/Library/Preferences/com.apple.loginitems.plist"
    guard let plistData = try? Data(contentsOf: URL(fileURLWithPath: plistPath)),
          let plistDict = try? PropertyListSerialization.propertyList(from: plistData, options: [], format: nil) as? [String: Any],
          let sessionItems = plistDict["SessionItems"] as? [String: Any],
          let customListItems = sessionItems["CustomListItems"] as? [[String: Any]] else {
        return false
    }
    
    let appBundleID = Bundle.main.bundleIdentifier ?? ""
    let appPath = Bundle.main.bundlePath
    
    for item in customListItems {
        // 检查Bundle ID或应用路径是否匹配
        if let itemBundleID = item["BundleID"] as? String, itemBundleID == appBundleID {
            return true
        }
        if let itemPath = item["Path"] as? String, itemPath == appPath {
            return true
        }
    }
    return false
}

注意事项

  • 该方法需要应用拥有完全磁盘访问权限(在系统设置「隐私与安全性」中开启),否则无法读取目标plist文件;
  • macOS 13及后续版本的登录项存储位置未发生变化,此方法兼容新旧系统。

方法二:通过AppleScript查询登录项

利用AppleScript可以直接查询系统登录项列表,应用内可通过NSAppleScript执行脚本实现判断:

Swift 示例代码

import Foundation

func isInLoginItemsViaAppleScript() -> Bool {
    let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? ""
    let script = """
    tell application "System Events"
        get the name of every login item whose name is "\(appName)"
    end tell
    """
    
    let appleScript = NSAppleScript(source: script)
    var error: NSDictionary?
    let result = appleScript?.executeAndReturnError(&error)
    
    if let error = error {
        print("AppleScript执行错误:\(error)")
        return false
    }
    
    return result?.stringValue != nil
}

注意事项

  • 此方法需要应用获得自动化权限(首次执行时系统会弹出权限请求);
  • 若应用名称存在重复,可能会出现误判,建议结合Bundle ID进行更精确的匹配(可修改AppleScript脚本,通过路径或Bundle ID查询)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:05:32