I would like to be able detect whether a mac is in the locked or asleep state via Objective-C. This question from 2012 provides half of the answer using the kCGSessionOnConsoleKey
key into the dictionary provided by CGSessionCopyCurrentDictionary()
.
CFDictionaryRef session = CGSessionCopyCurrentDictionary();
if (session != NULL) {
d->locked = ![[(id)session objectForKey:(NSString *)kCGSessionOnConsoleKey] boolValue]; // d's locked field name is not yet correct.
CFRelease(session);
}
The obvious next step of using a CGSSessionScreenIsLocked
key fails because it is not part of the dictionary's entries; TBH it's unclear how the linked answer worked given this, but I've seen many variations on the theme, so I guess it must have at some point.
Was CGSSessionScreenIsLocked
deprecated or does it live somewhere else? Is there an alternative approach to achieve this?
Unfortunately the fact that the key is not given under the official documentation page means nothing in the world of Cocoa framework. You can still access the key by specifying it as a raw string (rather than a constant), however be advised that while the screen is not locked, the corresponding value may not be present in the session dictionary. Here is how you may inspect current lock status in the form of a free function:
BOOL isScreenLocked() {
CFDictionaryRef session = CGSessionCopyCurrentDictionary();
const void *value;
if (CFDictionaryGetValueIfPresent(session, CFSTR("CGSSessionScreenIsLocked"), &value)) {
if (((__bridge NSNumber *)value).boolValue) {
return YES;
}
}
return NO;
}