如何在 iOS 中以编程方式禁用/启用睡眠模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12661004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:32:02  来源:igfitidea点击:

How to disable/enable the sleep mode programmatically in iOS?

ios

提问by Arnlee Vizcayno

I have an app that must stay awake until the end of a countdown but it will go into 'sleep mode' whenever it reaches the allocated time to sleep.

我有一个应用程序必须在倒计时结束前保持唤醒状态,但只要达到分配的睡眠时间,它就会进入“睡眠模式”。

In my app, I have the option to postpone sleep, so users can disable/enable it.

在我的应用程序中,我可以选择推迟睡眠,以便用户可以禁用/启用它。

How do I do it programmatically?

我如何以编程方式做到这一点?

回答by jrturton

You can disable the idle timer as follows;

您可以按如下方式禁用空闲计时器;

In Objective-C:

在 Objective-C 中:

[UIApplication sharedApplication].idleTimerDisabled = YES;

In Swift:

在斯威夫特:

UIApplication.sharedApplication().idleTimerDisabled = true

In Swift 3.0 & Swift 4.0:

在 Swift 3.0 和 Swift 4.0 中:

UIApplication.shared.isIdleTimerDisabled = true

Set it back to NOor falseto re-enable sleep mode.

将其设置回NOfalse重新启用睡眠模式。

For example, if you need it until you leave the view you can set it back by overriding the viewWillDisappear:

例如,如果您在离开视图之前需要它,您可以通过覆盖 viewWillDisappear 将其设置回来:

override func viewWillDisappear(_ animated: Bool) {
    UIApplication.shared.isIdleTimerDisabled = false
}

More about UIApplication Class.

更多关于UIApplication 类

回答by Wyetro

In Swift 3, to disable the idle timer it is now:

在 Swift 3 中,要禁用空闲计时器,现在是:

UIApplication.shared.isIdleTimerDisabled = true

To turn the idle timer back on it is simply:

重新打开空闲计时器很简单:

UIApplication.shared.isIdleTimerDisabled = false

Additionally, note that YESand NOare not available in Swift and that you must use either trueor false(as opposed to the previous answer).

此外,请注意YESNO在 Swift 中不可用,您必须使用truefalse(与上一个答案相反)。

回答by Sandeep Maurya

iOS 13, Swift 5,5.1+to disable the idle timer. In SceneDelegate.swift.

iOS 13, Swift 5,5.1+禁用空闲计时器。在SceneDelegate.swift.

 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
     UIApplication.shared.isIdleTimerDisabled = true
 }

回答by godblessstrawberry

in Swift 3 exact location where this can be done is AppDelegate.swift- you should add UIApplication.shared.isIdleTimerDisabled = trueinside applicationfunc so result will look like this:

在 Swift 3 中,可以完成此操作的确切位置是AppDelegate.swift- 您应该UIApplication.shared.isIdleTimerDisabled = trueapplicationfunc 中添加,因此结果将如下所示:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    UIApplication.shared.isIdleTimerDisabled = true
    return true
}