Disable sleep mode in OS X with swift

后端 未结 2 716
南笙
南笙 2021-01-05 15:08

I made an OS X Application in Xcode and I want to keep my Mac from going to sleep when I have it open. I know in iOS Swift you use:

UIApplication.sharedAppli         


        
相关标签:
2条回答
  • 2021-01-05 15:35

    If you are trying to prevent idle triggered sleep, IOCancelPowerCharge might work. But it won't work if something manually triggers the sleep

    0 讨论(0)
  • 2021-01-05 15:38

    The current way is shown in Technical QA 1340. It's ostensibly about sleep and wake notifications, but check out listing 2, entitled "Preventing sleep using I/O Kit in Mac OS X 10.6 Snow Leopard". You basically use IOPMAssertionCreateWithName to enter a state whereby sleep is disallowed, then call IOPMAssertionRelease when you're done.

    I don't have sample code, as I've not personally used this, but it'd be pretty straightforward to port the code in the tech note to Swift.

    Update: That API was introduced in 10.6, but still works fine in the latest OS, and as far as I know is still the preferred way to do it. Works in Swift, too.

    import IOKit
    import IOKit.pwr_mgt
    
    let reasonForActivity = "Reason for activity" as CFString
    var assertionID: IOPMAssertionID = 0
    var success = IOPMAssertionCreateWithName( kIOPMAssertionTypeNoDisplaySleep as CFString,
                                                IOPMAssertionLevel(kIOPMAssertionLevelOn), 
                                                reasonForActivity,
                                                &assertionID )
    if success == kIOReturnSuccess {
        // Add the work you need to do without the system sleeping here.
    
        success = IOPMAssertionRelease(assertionID);
        // The system will be able to sleep again.
    }
    
    0 讨论(0)
提交回复
热议问题