— Swift, Device Sleep, UIApplication — 1 min read
Preventing a device from sleeping is useful in many scenarios, for example, when playing audio or video, or when the user is actively using the app. In this article, we will discuss how to stop a device from sleeping using Swift.
To prevent the device from sleeping, we need to set the idleTimerDisabled
property of the UIApplication class to true
. This property is a Boolean value that determines whether the device should sleep or not. When set to true
, the device will not go to sleep, even when the user stops interacting with the device.
Here's how to set idleTimerDisabled
in Swift:
1UIApplication.shared.isIdleTimerDisabled = true
It is important to note that this property should only be set to true
when necessary and should be set back to false
as soon as possible to conserve the device's battery.
For example, if you are playing a video in your app and want to prevent the device from sleeping, you can set idleTimerDisabled
to true
before starting the video and set it back to false
when the video is finished:
1UIApplication.shared.isIdleTimerDisabled = true2// Play video here3UIApplication.shared.isIdleTimerDisabled = false
In conclusion, preventing a device from sleeping can be easily achieved in Swift by setting the idleTimerDisabled
property of the UIApplication class to true
. However, it should be used responsibly to conserve the device's battery.