Hasan Kassem
Hasan Kassem

Reputation: 145

Detect MacBook lid open/close with Swift?

Is there a way to detect MacBook lid open/close events in Swift? I searched a lot but didn't find a way in swift.

Upvotes: 0

Views: 901

Answers (1)

Hasan Kassem
Hasan Kassem

Reputation: 145

I managed to solve this problem by executing a terminal command in my app. Here is the code:

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
}

Upvotes: 5

Related Questions