How to prevent screen lock on my application with swift on IOS

断了今生、忘了曾经 提交于 2019-11-29 19:13:30
atwalsh

Use this:

Objective-C:

[[UIApplication sharedApplication] setIdleTimerDisabled: YES];

Swift (legacy):

UIApplication.sharedApplication().idleTimerDisabled = true

Swift 3/4:

UIApplication.shared.isIdleTimerDisabled = true

Make sure to import UIKit.

Here is the link to the documentation from apple.developer.com.

For Swift 3.0 here are two options depending on where you want to invoke the code:

Inside AppDelegate.swift:

application.idleTimerDisabled = true

Outside AppDelegate.swift:

UIApplication.shared().isIdleTimerDisabled = true

Swift 4

in AppDelegate.swift file, add the following line inside application function:

    application.isIdleTimerDisabled = true

You can use my little lib Insomnia (Swift 3, iOS 9+) - another nice feature is that you can prevent from sleeping only when charging.

The idleTimerDisabled soultion is okay but you have to remember to set it to false afterwards.

If you have more advanced case you can use our small project: ScreenSleepManager or if it's just about particular ViewControllers - use Insomnia as pointed earlier. Manual dealing with idleTimerDisabled almost always caused me some issues (like forgot to re-set to false or handle multiple (nested) modules trying to set it).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!