在开发过程中遇到电脑休眠网络断掉的问题,记录下来以便以后查阅。Mac系统如果设置了休眠,一段时间没有操作电脑,系统就会进入休眠模式,这是为了节能,延长电池的使用时间。但是如果我们开发的软件需要一直依赖网络,则不能让系统进入休眠模式。具体代码:
#pragma mark - 防止系统休眠
- (void)preventSystemSleep {
// 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.
}
}
只要调用preventSystemSleep这个方法,就可以使你的App在运行期间系统不会进入休眠模式,从而保障你的App顺利运行,不会出现断网等各种各样的问题。