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.
Open a Finder window, select Applications, right-click on an app, and select Get Info. Under General, select Prevent App Nap.
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!
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.
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")
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
Retain reference in a scope that will survive until any point you may want to revert the change (ie: within AppDelegate
)
var activity: NSObjectProtocol?
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With