11

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?

Community
  • 1
  • 1
Matt
  • 2,576
  • 6
  • 34
  • 52
  • 1
    Have you happened to find a solution to this? For UIApplication, this can be done: `UIApplication.shared.isIdleTimerDisabled = true`, but `isIdleTimerDisabled` isn't a member of `NSApplication`. I'd be happy if you found a solution. – Andreas is moving to Codidact Oct 01 '17 at 20:02
  • @Andreas unfortunately no I haven’t. – Matt Oct 02 '17 at 02:34

1 Answers1

11

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.

  • 3
    This seems to be working for me. I think it's noteworthy to state that you need to import IOKit and IOKit.pwr_mgt for this to work – Dustin Nielson Sep 09 '18 at 22:09
  • Also, this solution works for Mac Catalyst apps as long as the code above is contained in the appropriate architecture target tags. – adamjansch Feb 08 '22 at 16:26