苹果已经发布了关于这个主题的问答笔记,我相信它回答了你的问题。有问题的示例代码中的关键注释:
// 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.
}
用户显式触发睡眠(例如合上盖子或在 菜单中选择它)或系统使用电池供电时,仍然可以覆盖电源断言。
您在让代码正常工作时遇到问题吗?