PreventSleep is a simple library to prevent a Mac from allowing a display to sleep, or from prevent idle sleep.
It differs from another common approach on Mac which is to handle a caffeinate process.
import PreventSleep
import IOKit.pwr_mgt
let preventSleep = PreventSleep(
sleepAssertionMsg: "Prevent idle sleep when playing audio.",
sleepAssertionType: kIOPMAssertionTypeNoIdleSleep
)!
preventSleep.preventSleep()
sleep(10)
preventSlep.allowSleep()To check that the power assertion was correctly created/removed, run pmset -g assertions and look for your assertion.
Carthage
github "jesse-c/PreventSleep" ~> VERSION_NUMBER
Initialisation
PreventSleep(sleepAssertionMsg: String, sleepAssertionType)sleepAssertionMsg: String is the message that will be attached to the power assertion.
sleepAssertionType: String is either kIOPMAssertionTypeNoIdleSleep or kIOPMAssertionTypeNoDisplaySleep which are available after importing IOKit.pwr_mgt.
Prevent sleeping
preventSleep() -> BoolIndefinitely prevents the type of sleep specified. Returns true if a power assertion was create successfully, false otherwise.
Allow sleeping
allowSleep() -> BoolAllow the Mac to go to sleep following the user's energy prefernces. Returns true if a power assertion was removed successfully, false otherwise.
Check current sleeping status
canSleep() -> BoolReturns true if there is currently no power assertion preventing sleeping, false otherwise.
See Contributing.