I'm looking for a way to disable sleep mode and screensaver through my application using Swift. I know this question has been asked before, but none of the answers are current (at least for Swift; I don't know about Objective-C).
I originally thought to use NSWorkspace.sharedWorkspace().extendPowerOffBy(requested: Int)
, but according to Apple's documentation, it is currently unimplemented.
Any suggestions?
I recently came across this answer. It links to Q&A1340 at Apple, and translates listing 2 into Swift.
I refactored it into some different code, that shows how you can use them throughout the RunLoop
, for instance. I did check the code, and it works.
import IOKit.pwr_mgt
var noSleepAssertionID: IOPMAssertionID = 0
var noSleepReturn: IOReturn? // Could probably be replaced by a boolean value, for example 'isBlockingSleep', just make sure 'IOPMAssertionRelease' doesn't get called, if 'IOPMAssertionCreateWithName' failed.
func disableScreenSleep(reason: String = "Unknown reason") -> Bool? {
guard noSleepReturn == nil else { return nil }
noSleepReturn = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep as CFString,
IOPMAssertionLevel(kIOPMAssertionLevelOn),
reason as CFString,
&noSleepAssertionID)
return noSleepReturn == kIOReturnSuccess
}
func enableScreenSleep() -> Bool {
if noSleepReturn != nil {
_ = IOPMAssertionRelease(noSleepAssertionID) == kIOReturnSuccess
noSleepReturn = nil
return true
}
return false
}
The Q&A1340 answer also points out that using NSWorkspace.shared
should only be used to support OS X < 10.6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With