How to disable/enable the sleep mode programmatically in 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.


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
 }

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

Tags:

Ios