【问题标题】:Disable sleep mode in OS X with swift使用 swift 在 OS X 中禁用睡眠模式
【发布时间】:2016-04-20 23:54:17
【问题描述】:

我在 Xcode 中创建了一个 OS X 应用程序,我想让我的 Mac 在打开时不进入睡眠状态。我知道你在 iOS Swift 中使用:

UIApplication.sharedApplication().idleTimerDisabled = true

但是你如何使用 OS X Swift 做到这一点?

【问题讨论】:

标签: xcode swift macos


【解决方案1】:

当前方式显示在Technical QA 1340。它表面上是关于睡眠和唤醒通知,但请查看清单 2,标题为“Preventing sleep using I/O Kit in Mac OS X 10.6 Snow Leopard”。您基本上使用IOPMAssertionCreateWithName 进入不允许睡眠的状态,然后在完成后调用IOPMAssertionRelease

我没有示例代码,因为我没有亲自使用过,但是将技术说明中的代码移植到 Swift 会非常简单。

更新:该 API 在 10.6 中引入,但在最新的操作系统中仍然可以正常工作,据我所知,它仍然是首选方法。也适用于 Swift。

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.
}

【讨论】:

  • 感谢您提供帮助,但此答案适用于 OS X 10.6。我有 OS X 10.11。此代码也在 Objective-C 中。 Swift 直到 OS X 10.9 才出现。我需要 Swift 的代码。
  • @NathanaelCarper 这在 OS X 10.13 中完美运行。我将它重构为我自己的代码,发布here
  • 在 OS X 10.13.6 中运行良好。
【解决方案2】:

如果您试图防止空闲触发睡眠,IOCancelPowerCharge 可能会起作用。但是如果手动触发睡眠,它将不起作用

【讨论】:

  • 我该怎么做?我在网上找不到任何告诉我该怎么做的东西。
猜你喜欢
  • 2010-09-19
  • 1970-01-01
  • 2020-08-16
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多