使用Swift禁用OSX的睡眠/屏幕保护程序 [英] Using Swift to disable sleep/screen saver for OSX
问题描述
我正在寻找一种使用Swift使用我的应用程序禁用睡眠模式和屏幕保护程序的方法.我知道这
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).
我本来以为使用NSWorkspace.sharedWorkspace().extendPowerOffBy(requested: Int)
,但是根据
I originally thought to use NSWorkspace.sharedWorkspace().extendPowerOffBy(requested: Int)
, but according to Apple's documentation, it is currently unimplemented.
有什么建议吗?
推荐答案
我最近遇到了这个 answer .它链接到Apple的 Q& A1340 ,并翻译列表2进入Swift.
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
}
Q& A1340答案也指出使用NSWorkspace.shared
仅应用于支持OS X< 10.6.
The Q&A1340 answer also points out that using NSWorkspace.shared
should only be used to support OS X < 10.6.
这篇关于使用Swift禁用OSX的睡眠/屏幕保护程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!