【问题标题】:Using Swift to disable sleep/screen saver for OSX使用 Swift 禁用 OSX 的睡眠/屏幕保护程序
【发布时间】:2016-06-02 20:23:47
【问题描述】:

我正在寻找一种使用 Swift 通过我的应用程序禁用睡眠模式和屏幕保护程序的方法。我知道 questionbeen 询问过 before,但没有一个答案是当前(至少对于 Swift 而言;我不了解 Objective-C)。

本来想用NSWorkspace.sharedWorkspace().extendPowerOffBy(requested: Int),但是根据Apple's documentation,目前没有实现。

有什么建议吗?

【问题讨论】:

  • 您是否碰巧找到了解决方案?对于 UIApplication,可以这样做:UIApplication.shared.isIdleTimerDisabled = true,但isIdleTimerDisabled 不是NSApplication 的成员。如果您找到解决方案,我会很高兴。
  • @Andreas 不幸的是,我没有。

标签: swift macos cocoa


【解决方案1】:

我最近遇到了这个answer。它链接到 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
}

Q&A1340 answer 还指出使用NSWorkspace.shared 应该只用于支持 OS X

【讨论】:

  • 这似乎对我有用。我认为值得注意的是,您需要导入 IOKit 和 IOKit.pwr_mgt 才能正常工作
  • 此外,只要上述代码包含在适当的架构目标标签中,此解决方案就适用于 Mac Catalyst 应用程序。
猜你喜欢
  • 1970-01-01
  • 2012-06-08
  • 2023-03-31
  • 1970-01-01
  • 2011-04-09
  • 1970-01-01
  • 2018-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多