使用Swift为OSX禁用睡眠/屏幕保护程序

Mat*_*att 7 macos cocoa swift

我正在寻找一种方法来使用Swift通过我的应用程序禁用睡眠模式和屏幕保护程序.我知道这个问题已经之前,但没有一个答案是当前的(至少对于斯威夫特,我不知道的Objective-C).

我原本以为要使用NSWorkspace.sharedWorkspace().extendPowerOffBy(requested: Int),但根据Apple的文档,它目前尚未实现.

有什么建议?

And*_*er- 7

我最近遇到了这个答案。它链接到Apple 的Q&A1340,并将清单 2 翻译成 Swift。

我将它重构为一些不同的代码,例如,展示了如何在整个RunLoop. 我确实检查了代码,它有效。

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
}
Run Code Online (Sandbox Code Playgroud)

Q&A1340答案还指出,使用NSWorkspace.shared应该仅被用于支持OS X <10.6。

  • 这似乎对我有用。我认为值得注意的是,您需要导入 IOKit 和 IOKit.pwr_mgt 才能使其工作 (3认同)