如何在iOS上使用Swift防止应用程序锁屏

142

我如何仅在使用导航时防止屏幕锁定?

Waze有此选项,我的应用程序该如何实现?

6个回答

287

使用以下内容:

Objective-C:

[[UIApplication sharedApplication] setIdleTimerDisabled: YES];

Swift(旧版):

UIApplication.sharedApplication().idleTimerDisabled = true

Swift 3及以上版本:

UIApplication.shared.isIdleTimerDisabled = true

请确保导入UIKit

这里是来自developer.apple.com的文档链接。


4
Swift应该是UIApplication.sharedApplication().idleTimerDisabled = true - Doug
4
Swift 3:UIApplication.shared.idleTimerDisabled = true - funkenstrahlen
3
它被修改为 UIApplication.shared.isIdleTimerDisabled = true - Lucas Farah
1
在哪里添加这行代码?我没有AppDelegate.swift文件,因为我正在使用React Native。 - Pradnyanand Milind Pohare
@PradnyanandMilindPohare 你可以把它添加到任何地方,只要确保这行代码被执行。 - Mellao

25

针对 Swift 3.0,这里有两个选项,取决于您想在哪里调用代码:

在 AppDelegate.swift 中:

application.idleTimerDisabled = true

在 AppDelegate.swift 之外:

UIApplication.shared().isIdleTimerDisabled = true


3
AppDelegate.swift 之外的代码应该像这样:UIApplication.shared.isIdleTimerDisabled = false - DevStarlight

16

Swift 4

在 AppDelegate.swift 文件中,在 application 函数内部添加以下行:

application.isIdleTimerDisabled = true
        

6
你可以使用我的小库 Insomnia(Swift 3,iOS 9+) - 另一个很好的功能是仅在充电时防止休眠。 idleTimerDisabled 解决方案还不错,但你必须记得在之后将其设置为 false

1
SwiftUI 代码:
struct ContentView: View {
    var body: some View {
        VStack {
            Text("Prevent Screen Sleep")
        }
        .onAppear {
            // Disable the idle timer when the view appears
            UIApplication.shared.isIdleTimerDisabled = true
        }
        .onDisappear {
            // Re-enable the idle timer when the view disappears
            UIApplication.shared.isIdleTimerDisabled = false
        }
    }
}

0

如果您有更高级的情况,可以使用我们的小项目:ScreenSleepManager,或者如果只是关于特定的ViewControllers - 如前所述,请使用Insomnia。手动处理idleTimerDisabled几乎总是会导致一些问题(例如忘记重新设置为false或处理尝试设置它的多个(嵌套)模块)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接