I can\'t find any instructions how to put a Mac programmatically into sleep mode (in Objective-C). I\'m sure it should be only one line, but could you give me a hint?
Just in case someone is curious how pmset sleepnow
actually works - it uses IOPMSleepSystem API from the Power Management section of the IOKit framework. You can check this via examining the pmset.c source code (link from macOS 10.13.3).
So instead of calling pmset
you can request sleep via the following snippet:
#include
void SleepNow()
{
io_connect_t fb = IOPMFindPowerManagement(MACH_PORT_NULL);
if (fb != MACH_PORT_NULL)
{
IOPMSleepSystem(fb);
IOServiceClose(fb);
}
}
Don't be scared by the caller must be root or the console user remark in the documentation since it appears to be working for any standard logged in user.
By following the source code, it looks like it calls into IOUserClient::clientHasPrivilege
with kIOClientPrivilegeLocalUser
which ends up checking if the caller is present in the IOConsoleUsers
array in the root IORegistry entry, and apparently currently logged in user is always present there.