Skip to content

Instantly share code, notes, and snippets.

@macshome
Created October 30, 2023 19:05
Show Gist options
  • Save macshome/8ad9456806a6501ef7dba20a2ec856e3 to your computer and use it in GitHub Desktop.
Save macshome/8ad9456806a6501ef7dba20a2ec856e3 to your computer and use it in GitHub Desktop.
Paste into a Swift playground on macOS to see if your screen is locked
import Cocoa
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
var isScreenLocked: Bool {
guard let wssProperties = CGSessionCopyCurrentDictionary() as? [String : Any], (wssProperties["CGSSessionScreenIsLocked"] != nil) else {
return false
}
return true
}
Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { _ in
print(isScreenLocked)
}
@macshome
Copy link
Author

Shows how to use the CGSSessionScreenIsLocked attribute to know if the screen on a Mac is locked at that time. You can start this running, lock your screen, then unlock and check to see the results.

This code is using a simple timer, but you could just listen for kCGNotifyGUIConsoleSessionChanged to be posted and then check to see if it is locked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment