【问题标题】:Detect MacBook lid open/close with Swift?使用 Swift 检测 MacBook 盖子打开/关闭?
【发布时间】:2019-12-22 17:57:55
【问题描述】:

有没有办法在 Swift 中检测 MacBook 盖子打开/关闭事件? 我搜索了很多,但没有找到快速的方法。

【问题讨论】:

  • 检测睡眠/唤醒是否“足够好”?
  • @Alexander-ReinstateMonica 我需要检测合上盖子
  • 如果它连接到外部显示器并在盖子关闭的情况下运行怎么办?

标签: swift xcode macos cocoa


【解决方案1】:

我设法通过在我的应用程序中执行终端命令来解决这个问题。代码如下:

func lidClosed() -> Bool {
    let pipe = Pipe()
    let process = Process()
    process.launchPath = "/bin/sh"
    process.arguments = ["-c", "ioreg -r -k AppleClamshellState -d 4 | grep AppleClamshellState  | head -1"]
    process.standardOutput = pipe
    let fileHandle = pipe.fileHandleForReading
    process.launch()
    if(String(data: fileHandle.readDataToEndOfFile(), encoding: .utf8)?.contains("Yes") ?? false){
        return true
    }
    return false
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2011-09-04
    • 2017-12-29
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多