swift - 使用 Swift 禁用 OSX 的 sleep /屏幕保护程序

标签 swift macos cocoa

我正在寻找一种使用 Swift 通过我的应用程序禁用 sleep 模式和屏幕保护程序的方法。我知道这个 questionbeenbefore ,但没有一个答案是最新的(至少对于 Swift 而言;我不知道 Objective-C)。

我最初想使用 NSWorkspace.sharedWorkspace().extendPowerOffBy(requested: Int),但根据 Apple's documentation , 目前尚未实现。

有什么建议吗?

最佳答案

我最近遇到了这个answer .它链接到 Q&A1340在 Apple,并将 list 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 < 10.6。

关于swift - 使用 Swift 禁用 OSX 的 sleep /屏幕保护程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37601453/

相关文章:

swift - 如何在 Mac Catalyst 13.0+ swift 中打开 Finder

node.js - 在 Mac 上更改计算机名称后出现 Node JS 错误 EADDRNOTAVAIL

objective-c - mac osx 中的亚马逊 s3?

objective-c - 如何在 NSTextView 中绘制特定范围文本的背景

ios - 在 collectionview 中选择和取消选择行时出错

ios - 如何从 react native 桥将参数传递给 swift 类

ios - iPad 和 iPhone 上的 UIScrollView 分页布局

macos - 在 OS X 上部署独立的 GUI Perl 应用程序

objective-c - 更改 View 会将它们重新定位在 (0,0)

objective-c - 在 Objective-C 中的最后一项之前创建一个逗号分隔的列表,其中包含 "and",特别是