I made an OS X Application in Xcode and I want to keep my Mac from going to sleep when I have it open. I know in iOS Swift you use:
UIApplication.sharedApplication().idleTimerDisabled = true
But how do you do it with OS X Swift?
The current way is shown in Technical QA 1340. It's ostensibly about sleep and wake notifications, but check out listing 2, entitled "Preventing sleep using I/O Kit in Mac OS X 10.6 Snow Leopard". You basically use IOPMAssertionCreateWithName
to enter a state whereby sleep is disallowed, then call IOPMAssertionRelease
when you're done.
I don't have sample code, as I've not personally used this, but it'd be pretty straightforward to port the code in the tech note to Swift.
Update: That API was introduced in 10.6, but still works fine in the latest OS, and as far as I know is still the preferred way to do it. Works in Swift, too.
import IOKit
import IOKit.pwr_mgt
let reasonForActivity = "Reason for activity" as CFString
var assertionID: IOPMAssertionID = 0
var success = IOPMAssertionCreateWithName( kIOPMAssertionTypeNoDisplaySleep as CFString,
IOPMAssertionLevel(kIOPMAssertionLevelOn),
reasonForActivity,
&assertionID )
if success == kIOReturnSuccess {
// Add the work you need to do without the system sleeping here.
success = IOPMAssertionRelease(assertionID);
// The system will be able to sleep again.
}
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