Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable sleep mode in OS X with swift

Tags:

xcode

macos

swift

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?

like image 725
Nathanael Carper Avatar asked Apr 20 '16 23:04

Nathanael Carper


1 Answers

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.
}
like image 172
zpasternack Avatar answered Oct 03 '22 23:10

zpasternack