Matt
Matt

Reputation: 2722

Using Swift to disable sleep/screen saver for OSX

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?

Upvotes: 13

Views: 3151

Answers (1)

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.

Upvotes: 19

Related Questions