我如何仅在使用导航时防止屏幕锁定?
Waze有此选项,我的应用程序该如何实现?
使用以下内容:
Objective-C:
[[UIApplication sharedApplication] setIdleTimerDisabled: YES];
Swift(旧版):
UIApplication.sharedApplication().idleTimerDisabled = true
Swift 3及以上版本:
UIApplication.shared.isIdleTimerDisabled = true
请确保导入UIKit
。
这里是来自developer.apple.com的文档链接。
针对 Swift 3.0,这里有两个选项,取决于您想在哪里调用代码:
在 AppDelegate.swift 中:
application.idleTimerDisabled = true
在 AppDelegate.swift 之外:
UIApplication.shared().isIdleTimerDisabled = true
UIApplication.shared.isIdleTimerDisabled = false
。 - DevStarlightSwift 4
在 AppDelegate.swift 文件中,在 application 函数内部添加以下行:
application.isIdleTimerDisabled = true
idleTimerDisabled
解决方案还不错,但你必须记得在之后将其设置为 false
。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
}
}
}
如果您有更高级的情况,可以使用我们的小项目:ScreenSleepManager,或者如果只是关于特定的ViewControllers - 如前所述,请使用Insomnia。手动处理idleTimerDisabled
几乎总是会导致一些问题(例如忘记重新设置为false或处理尝试设置它的多个(嵌套)模块)。
UIApplication.sharedApplication().idleTimerDisabled = true
。 - DougUIApplication.shared.idleTimerDisabled = true
- funkenstrahlenUIApplication.shared.isIdleTimerDisabled = true
。 - Lucas Farah