Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Swift to disable sleep/screen saver for OSX

Tags:

macos

swift

cocoa

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?

like image 624
Matt Avatar asked Jun 02 '16 20:06

Matt


1 Answers

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.

like image 92
Andreas detests censorship Avatar answered Oct 06 '22 00:10

Andreas detests censorship