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

Ios

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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.

Solution 2 - Ios

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).

Solution 3 - Ios

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
 }

Solution 4 - Ios

in Swift 3 exact location where this can be done is AppDelegate.swift - you should add UIApplication.shared.isIdleTimerDisabled = true inside application func so result will look like this:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    UIApplication.shared.isIdleTimerDisabled = true
    return true
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArnlee VizcaynoView Question on Stackoverflow
Solution 1 - IosjrturtonView Answer on Stackoverflow
Solution 2 - IosWyetroView Answer on Stackoverflow
Solution 3 - IosSandeep MauryaView Answer on Stackoverflow
Solution 4 - IosgodblessstrawberryView Answer on Stackoverflow