How do I prevent a device from going into sleep mode?

I want my app to decide whether sleep mode should be enabled by checking how many bluetooth peripherals are connected. For bluetooth I created a Singleton, which contains an array of all the connected peripherals. To disable sleep mode I found the following line of code online:

UIApplication.shared.isIdleTimerDisabled = true

Since the state of the sleep mode should always be updated after the number of connected peripherals changed, I could not figure out where to put that line of code.

Sorry if that's a novice question, but I am pretty new to programming, so I would appreciate any help. Maybe there is a better way to achieve the wanted behavior and I would be happy to learn about it.

Thanks in advance.

You should implement this where you want to disable.

And return to false when no more need.


Can be done in viewDidLoad for instance, and restore in viewWillDisappear.

Or, for more general application, in appDidFinishLaunching.


Take care to follow the notice:


Discussion

The default value of this property is

false
. When most apps have no touches as user input for a short period, the system puts the device into a "sleep” state where the screen dims. This is done for the purposes of conserving power. However, apps that don't have user input except for the accelerometer—games, for instance—can, by setting this property to
true
, disable the “idle timer” to avert system sleep.

Important

You should set this property only if necessary and should be sure to reset it to

false
when the need no longer exists. Most apps should let the system turn off the screen when the idle timer elapses. This includes audio apps. With appropriate use of Audio Session Services, playback and recording proceed uninterrupted when the screen turns off. The only apps that should disable the idle timer are mapping apps, games, or programs where the app needs to continue displaying content when user interaction is minimal.

Since I am using SwiftUI there is no viewDidLoad() function. Furthermore it should always be updated after a peripheral connected or disconnected.

You can do some setup in SceneDelegate willConnectTo.


For dynamic update, I would create observableObject.


See some hints here:

https://stackoverflow.com/questions/58239721/render-list-after-bluetooth-scanning-starts-swiftui

How do I prevent a device from going into sleep mode?
 
 
Q