Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

I am building an app, and on one specific viewController I want to disable the sleep mode.

I have 3 questions:

  1. I am using this code in the viewDidLoad method of the specific view controller:

    UIApplication.sharedApplication().idleTimerDisabled = true

    Reading previous questions about this, I am convinced this is the correct code. But is this the correct 'place' in the code?

  2. Should I use the following code on the other view controllers (or is this not necessary, will it go to default without?):

    UIApplication.sharedApplication().idleTimerDisabled = false

  3. In the simulator I use Hardware -> Lock to simulate lockscreen. Do you think this will always just lock the screen? Or will it not lock (sleep mode) my app on the specific view controller if my code is correct? (bc now it just locks it in the simulator). How can I simulate idle time of the user?

like image 643
codeDude Avatar asked Dec 24 '22 14:12

codeDude


1 Answers

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.

like image 60
Adrian Avatar answered Dec 31 '22 14:12

Adrian