macOS 14及以后com.apple.dock.plist变更,求Dock设置获取替代方案
macOS 14+ 获取原生Dock设置的替代方案
问题背景
我们正在开展一个企业项目,需通过~/Library/Preferences/com.apple.dock.plist文件获取原生Dock的详细设置(如自动隐藏、方向)。该方法在macOS 13.*及之前版本均可正常工作,但在macOS 14.*及以后版本中,该文件已发生变更。
此前使用的代码如下:
if let defaults = UserDefaults(suiteName: "com.apple.dock"), let orientation = defaults.string(forKey: "orientation") { // 处理获取到的方向设置 }
请问在macOS 14.*及以后版本中,是否有替代方法实现这一需求?
可行替代方案
1. 通过defaults命令行工具读取
调用系统自带的defaults命令读取Dock配置,再在代码中解析返回的Plist数据,示例Swift代码:
import Foundation func fetchDockSettings() -> [String: Any]? { let process = Process() process.executableURL = URL(fileURLWithPath: "/usr/bin/defaults") process.arguments = ["read", "com.apple.dock"] let outputPipe = Pipe() process.standardOutput = outputPipe do { try process.run() process.waitUntilExit() let resultData = outputPipe.fileHandleForReading.readDataToEndOfFile() guard let dockPlist = try? PropertyListSerialization.propertyList(from: resultData, options: [], format: nil) as? [String: Any] else { return nil } return dockPlist } catch { print("获取Dock配置失败: \(error.localizedDescription)") return nil } } // 使用示例 if let dockConfig = fetchDockSettings() { let orientation = dockConfig["orientation"] as? String ?? "未知" let isAutoHideEnabled = dockConfig["autohide"] as? Bool ?? false print("Dock方向:\(orientation),自动隐藏状态:\(isAutoHideEnabled)") }
2. 使用AppleScript读取系统设置
AppleScript可直接访问Dock的配置项,Swift中可通过NSAppleScript类调用脚本,示例:
import Foundation // 获取Dock方向 func getDockOrientation() -> String? { let scriptContent = """ tell application "System Events" return orientation of dock end tell """ let appleScript = NSAppleScript(source: scriptContent) let executionResult = appleScript?.executeAndReturnError(nil) return executionResult?.stringValue } // 获取Dock自动隐藏状态 func getDockAutoHideStatus() -> Bool? { let scriptContent = """ tell application "System Events" return autohide of dock end tell """ let appleScript = NSAppleScript(source: scriptContent) let executionResult = appleScript?.executeAndReturnError(nil) return executionResult?.booleanValue } // 使用示例 if let orientation = getDockOrientation() { print("Dock当前方向:\(orientation)") } if let autoHide = getDockAutoHideStatus() { print("Dock自动隐藏:\(autoHide ? "开启" : "关闭")") }
权限说明
使用上述方法需在项目的Info.plist中添加NSAppleEventsUsageDescription键,填写访问系统设置的用途说明,否则会被系统拦截权限请求。
内容的提问来源于stack exchange,提问作者Khang
相关产品推荐
相关产品推荐

