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.

  • optimization - stepping may behave oddly : iOS/Unity
  • In Swift, how can I change an attribute of part of a string?
  • Swift access to C Struct
  • How to add data to HTTPBody with PUT method in NSURLSession?
  • didUpdateLocations not being called
  • NSURL from String gets truncated, dots on the UIVideoEditorController's video path Swift 2 iOS 8
  • Any suggestions?

    Solutions Collect From Internet About “Using Swift to disable sleep/screen saver for OSX”

    I recently came across this answer. It links to Q&A1340 at Apple, and translates listing 2 into Swift.

    I did refactor into some different code, that shows how you can use them throughout loops, for instance. I did check the code, and it works.

    var assertionID: IOPMAssertionID = 0
    var success: IOReturn?
    func disableScreenSleep(reason: String = "Unknown reason") -> Bool? {
        guard success != nil else { return nil }
        success = IOPMAssertionCreateWithName( kIOPMAssertionTypeNoDisplaySleep as CFString,
                                               reason as CFString,
                                               &assertionID )
        return success == kIOReturnSuccess
    func  enableScreenSleep() -> Bool {
        if success != nil {
            success = IOPMAssertionRelease(noSleepAssertionID)
            success = 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.