Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable app nap in Swift

Tags:

xcode

macos

swift

How do I disable app nap in Swift? Im new to programming and I am building a timer(just for practice), and I am afraid app nap will break my timer.

like image 635
Vitor Loureiro Avatar asked Dec 26 '14 07:12

Vitor Loureiro


People also ask

How do I turn off app nap on Mac?

Open a Finder window, select Applications, right-click on an app, and select Get Info. Under General, select Prevent App Nap.

How do I keep the screen awake in Swift?

You can stop the iOS screen sleeping by using the isIdleTimerDisabled property of your application. When set to true, this means the screen will never dim or go to sleep while your app is running, so be careful – you don't want to waste your user's battery life!

What is Nap app?

App Nap is a related optimization, blocking inactive applications from using the CPU and other system resources. This keeps your computer's resources free, and saves battery life.


2 Answers

I found that this solution works in Swift as well.

Create a class or global variable

var activity: NSObjectProtocol?

And assign it after which App Nap will be disabled

activity = NSProcessInfo().beginActivityWithOptions(NSActivityOptions.UserInitiated, reason: "Good Reason")
like image 152
Mellson Avatar answered Oct 01 '22 02:10

Mellson


Swift 4.x / 5.3:

For ProcessInfo.ActivityOptions, Apple's documentation describes:

static var userInitiated

Flag to indicate the app is performing a user-requested action.

static var userInitiatedAllowingIdleSystemSleep

Flag to indicate the app is performing a user-requested action, but that the system can sleep on idle.

Unless your intention is to prevent the system from sleeping, you should use userInitiatedAllowingIdleSystemSleep.

Steps

  1. Retain reference in a scope that will survive until any point you may want to revert the change (ie: within AppDelegate)

     var activity: NSObjectProtocol?
    
  2. Run this, possibly in AppDelegate applicationDidFinishLaunching:

     activity = ProcessInfo.processInfo.beginActivity(options: .userInitiatedAllowingIdleSystemSleep, reason: "Good Reason")
    

To cancel and re-enable App Nap at any time:

if let pinfo = activity {
    ProcessInfo.processInfo.endActivity(pinfo)
}
like image 25
stef Avatar answered Oct 01 '22 02:10

stef