swiftxcodemacossleep

How to put Mac to sleep programmatically with Swift


I am writing a program to make my MacBook Pro go to sleep when the app opens but I can't seem to figure it out. I don't know if this is something to do with power management or something but from what I found on is that it has something to do with IOKit.pwr_mgt. Your help would be appreciated! The code below is just how to enable sleep mode but not put the computer into sleep mode. I also found the applicationDidFinishLaunching function so the code is in that function.

var assertionID: IOPMAssertionID = 0
var success = IOPMAssertionRelease(assertionID)

Solution

  • It is not related to power management. You will actually need to run a script with your app.

    The easiest way to accomplish this is first disable your App sandbox capability.

    Next go to your app info.plist and add NSAppleEventsUsageDescription key and a description, something like "This app needs your permission to put the display to sleep.".

    Now you just need to execute an Apple script telling application system events to sleep. "tell application \"System Events\" to sleep":

    Create a method to execute that script:

    func startScreenSleep() {
        let script = "tell application \"System Events\" to sleep"
        guard let appleScript = NSAppleScript(source: script) else { return }
        var error: NSDictionary?
        appleScript.executeAndReturnError(&error)
        if let error = error {
            print(error[NSAppleScript.errorAppName] as! String)
            print(error[NSAppleScript.errorBriefMessage] as! String)
            print(error[NSAppleScript.errorMessage] as! String)
            print(error[NSAppleScript.errorNumber] as! NSNumber)
            print(error[NSAppleScript.errorRange] as! NSRange)
        }
    }
    

    And call it from your ViewController's viewDidLoad method:

    override func viewDidLoad() {
        super.viewDidLoad()
        startScreenSleep()
    }