Mac開發之防止系統進入休眠模式

在開發過程中遇到電腦休眠網絡斷掉的問題,記錄下來以便以後查閱。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順利運行,不會出現斷網等各種各樣的問題。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章