Skip to content

Instantly share code, notes, and snippets.

@asus4
Last active March 11, 2024 15:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asus4/9910335 to your computer and use it in GitHub Desktop.
Save asus4/9910335 to your computer and use it in GitHub Desktop.
Prevent sleep and screensaver while the application running. ref: http://qiita.com/asus4/items/02b5096a937bbd419f3e
//
// LittleCaffeine.h
//
// This is tiny utility inspired by Caffeine http://lightheadsw.com/caffeine/
//
// Created by Koki Ibukuro on 2014/04/01.
// Copyright (c) 2014年 Koki Ibukuro. All rights reserved.
//
#pragma once
#ifndef Little_Caffeine_h
#define Little_Caffeine_h
#import <Foundation/Foundation.h>
#import <IOKit/pwr_mgt/IOPMLib.h>
static IOPMAssertionID assertionID;
static BOOL LittleCaffeineEnable() {
// https://developer.apple.com/library/mac/qa/qa1340/_index.html
CFStringRef reasonForActivity= CFSTR("Little Caffeine for Wake Up");
IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
kIOPMAssertionLevelOn, reasonForActivity, &assertionID);
if (success == kIOReturnSuccess) {
return YES;
}
else {
assertionID = -1;
return NO;
}
}
static BOOL LittleCaffeineDisable() {
IOReturn success = NO;
if(assertionID > 0) {
success = IOPMAssertionRelease(assertionID);
}
if(success == kIOReturnSuccess) {
return YES;
}
else {
return NO;
}
}
#endif
//
// LittleCaffeine.swift
//
// This is tiny utility inspired by Caffeine http://lightheadsw.com/caffeine/
//
// Created by Koki Ibukuro on 2024/03/11
// Copyright (c) 2024 Koki Ibukuro. All rights reserved.
//
import IOKit.pwr_mgt
struct LittleCaffeine {
private static var assertionID: IOPMAssertionID = .init(0)
static func Enable() -> Bool {
let reasonForActivity = "Little Caffeine for Wake Up" as CFString
let success = IOPMAssertionCreateWithName(kIOPMAssertPreventUserIdleDisplaySleep as CFString,
IOPMAssertionLevel(kIOPMAssertionLevelOn),
reasonForActivity,
&assertionID)
if success == kIOReturnSuccess {
return true
} else {
assertionID = IOPMAssertionID(0)
return false
}
}
static func Disable() -> Bool {
var success = kIOReturnError
if assertionID > 0 {
success = IOPMAssertionRelease(assertionID)
assertionID = IOPMAssertionID(0)
}
return success == kIOReturnSuccess
}
}
#import "LittleCaffeine.h"
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
LittleCaffeineEnable();
}
- (void) applicationWillTerminate:(NSNotification *)notification
{
LittleCaffeineDisable();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment