8

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?

Nathanael Carper
  • 302
  • 3
  • 17
  • Take a look at the source for the `caffeinate` command: http://opensource.apple.com/source/PowerManagement/PowerManagement-321.2.9/caffeinate/caffeinate.c – jtbandes Apr 21 '16 at 01:10

2 Answers2

14

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.
}
zpasternack
  • 17,838
  • 2
  • 63
  • 81
-1

If you are trying to prevent idle triggered sleep, IOCancelPowerCharge might work. But it won't work if something manually triggers the sleep

notacommie
  • 1
  • 1
  • 6