Arnlee Vizcayno
Arnlee Vizcayno

Reputation: 2426

How to disable/enable the sleep mode programmatically in iOS?

I have an app that must stay awake until the end of a countdown but it will go into 'sleep mode' whenever it reaches the allocated time to sleep.

In my app, I have the option to postpone sleep, so users can disable/enable it.

How do I do it programmatically?

Upvotes: 166

Views: 79247

Answers (3)

Sandeep Maurya
Sandeep Maurya

Reputation: 2099

iOS 13, Swift 5,5.1+ to disable the idle timer. In SceneDelegate.swift.

 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
     UIApplication.shared.isIdleTimerDisabled = true
 }

Upvotes: 4

Wyetro
Wyetro

Reputation: 8588

In Swift 3, to disable the idle timer it is now:

UIApplication.shared.isIdleTimerDisabled = true

To turn the idle timer back on it is simply:

UIApplication.shared.isIdleTimerDisabled = false

Additionally, note that YES and NO are not available in Swift and that you must use either true or false (as opposed to the previous answer).

Upvotes: 25

jrturton
jrturton

Reputation: 119242

You can disable the idle timer as follows;

In Objective-C:

[UIApplication sharedApplication].idleTimerDisabled = YES;

In Swift:

UIApplication.sharedApplication().idleTimerDisabled = true

In Swift 3.0 & Swift 4.0:

UIApplication.shared.isIdleTimerDisabled = true

Set it back to NO or false to re-enable sleep mode.

For example, if you need it until you leave the view you can set it back by overriding the viewWillDisappear:

override func viewWillDisappear(_ animated: Bool) {
    UIApplication.shared.isIdleTimerDisabled = false
}

More about UIApplication Class.

Upvotes: 394

Related Questions