How to Disable/Enable the Sleep Mode Programmatically in iOS

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.

How to disable/enable the sleep mode programmatically for a specific view controller?

You'll want to disable the idleTimer in viewDidLoad

UIApplication.shared.isIdleTimerDisabled = true

You'll want to re-enable idleTimer when yourViewController disappears, so put this in viewDidDisappear

UIApplication.shared.isIdleTimerDisabled = false

You manually lock the screen by pressing the power button button, which is what happens when you manually lock the screen from the simulator. When you do this, your view disappears, so the idleTimer should be disabled. You can test that that's the case by putting a print statement in viewDidDisappear.

The way you would set idleTimer in iOS is going to Settings->General->Auto-Lock and specifying the length of time that should pass before the screen locks. The shortest interval is 1 minute. If you leave it alone and don't press the power button, the idleTimer should be disabled.

How to disable sleep mode of Apple watch programmatically

As of my knowledge and recent search on this topic, There is currently no api available to enable/disable sleep mode for Apple Watch programmatically.

How to re-enable the idle timer in ios once it has been disabled (to allow the display to sleep again)?

Are you trying this when you Run from Xcode? Running from Xcode always disables the idle timer, regardless if you set [UIApplication sharedApplication].idleTimerDisabled or not. You can try it by manually opening the app from the iPhone/iPod touch/iPad.

Force iPad to stay awake while app is running a process

While you can disable the sleep mode programmatically, your correct approach here is to fix the bug.

You cannot prevent the user from switching the device off manually anyway.

iPhone: Can I programmatically disable auto turning off the display?

In AppDelegate add:

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions...

//Add this to your method
[UIApplication sharedApplication].idleTimerDisabled = YES;


Related Topics



Leave a reply



Submit