有没有办法防止Mac使用Objective-C以编程方式进入睡眠状态? Apple开发站点上的I / O套件基础知识部分告诉我,驱动程序会收到有关空闲/系统睡眠的通知,但我找不到防止系统睡眠的方法。可能吗?
我遇到了一些其他使用Caffeine,Jiggler,sleepless甚至AppleScript的解决方案,但是我想在Objective-C中做到这一点。谢谢。
最佳答案
这是Apple的官方文档(包括代码片段):
Technical Q&A QA1340 - How to I prevent sleep?
Quote:在Mac OS X 10.6 Snow Leopard中使用I / O Kit防止睡眠:
#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?
Quote:使用UpdateSystemActivity的示例(
#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/5596319/