快速禁用OS X中的睡眠模式 [英] Disable sleep mode in OS X with swift

查看:128
本文介绍了快速禁用OS X中的睡眠模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I made an OS X Application in Xcode and I want to keep my Mac from going to sleep when I have it open. I know in iOS Swift you use:

UIApplication.sharedApplication().idleTimerDisabled = true

但是您如何使用OS X Swift?

But how do you do it with OS X Swift?

推荐答案

当前方法显示在技术质量检查1340 .表面上它与睡眠和唤醒通知有关,但请查看清单2,标题为在Mac OS X 10.6 Snow Leopard中使用I/O Kit防止睡眠".基本上,您使用IOPMAssertionCreateWithName进入不允许睡眠的状态,然后在完成后调用IOPMAssertionRelease.

The current way is shown in Technical QA 1340. It's ostensibly about sleep and wake notifications, but check out listing 2, entitled "Preventing sleep using I/O Kit in Mac OS X 10.6 Snow Leopard". You basically use IOPMAssertionCreateWithName to enter a state whereby sleep is disallowed, then call IOPMAssertionRelease when you're done.

我没有示例代码,因为我个人没有使用它,但是将技术说明中的代码移植到Swift会非常简单.

I don't have sample code, as I've not personally used this, but it'd be pretty straightforward to port the code in the tech note to Swift.

更新:该API是在10.6中引入的 ,但在最新的OS中仍然可以正常使用,据我所知,它仍然是首选的实现方式.在Swift中也可以使用.

Update: That API was introduced in 10.6, but still works fine in the latest OS, and as far as I know is still the preferred way to do it. Works in Swift, too.

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中的睡眠模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆