gpt4 book ai didi

objective-c - 如何以编程方式阻止 Mac 进入休眠状态?

转载 作者:行者123 更新时间:2023-11-30 13:11:00 24 4
gpt4 key购买 nike

有没有办法使用 Objective-C 以编程方式阻止 Mac 进入休眠状态? Apple 开发网站上的 I/O 套件基础知识部分告诉我,驱动程序会收到空闲/系统 sleep 的通知,但我找不到阻止系统 sleep 的方法。这可能吗?

我遇到过一些使用 Caffeine、jiggler、sleepless 甚至 AppleScript 的其他解决方案,但我想在 Objective-C 中做到这一点。谢谢。

最佳答案

这里是苹果官方文档(包括代码片段):
Technical Q&A QA1340 - How to I prevent sleep?

引用:在 Mac OS X 10.6 Snow Leopard 中使用 I/O Kit 防止 sleep :

#import <IOKit/pwr_mgt/IOPMLib.h>

// kIOPMAssertionTypeNoDisplaySleep prevents display sleep,
// kIOPMAssertionTypeNoIdleSleep prevents idle sleep

// reasonForActivity is a descriptive string used by the system whenever it needs
// to tell the user why the system is not sleeping. For example,
// "Mail Compacting Mailboxes" would be a useful string.

// NOTE: IOPMAssertionCreateWithName limits the string to 128 characters.
CFStringRef* reasonForActivity= CFSTR("Describe Activity Type");

IOPMAssertionID assertionID;
IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
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.
}

对于较旧的 OSX 版本,请检查以下内容:
Technical Q&A QA1160 - How can I prevent system sleep while my application is running?

引用: UpdateSystemActivity 的示例用法(< 10.6 的规范方式)

#include <CoreServices/CoreServices.h>

void
MyTimerCallback(CFRunLoopTimerRef timer, void *info)
{
UpdateSystemActivity(OverallAct);
}


int
main (int argc, const char * argv[])
{
CFRunLoopTimerRef timer;
CFRunLoopTimerContext context = { 0, NULL, NULL, NULL, NULL };

timer = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent(), 30, 0, 0, MyTimerCallback, &context);
if (timer != NULL) {
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes);
}

/* Start the run loop to receive timer callbacks. You don't need to
call this if you already have a Carbon or Cocoa EventLoop running. */
CFRunLoopRun();

CFRunLoopTimerInvalidate(timer);
CFRelease(timer);

return (0);
}

关于objective-c - 如何以编程方式阻止 Mac 进入休眠状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38736343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com