如何在IOS上使用swift防止我的应用程序上的屏幕锁定

alv*_*lia 100 locking screen ios swift

如何仅在使用导航时阻止屏幕锁定.Waze可以选择这样做,我怎样才能在我的应用程序中执行此操作?

atw*_*lsh 219

用这个:

Objective-C的:

[[UIApplication sharedApplication] setIdleTimerDisabled: YES];
Run Code Online (Sandbox Code Playgroud)

Swift(遗产):

UIApplication.sharedApplication().idleTimerDisabled = true
Run Code Online (Sandbox Code Playgroud)

迅捷3/4:

UIApplication.shared.isIdleTimerDisabled = true
Run Code Online (Sandbox Code Playgroud)

确保导入UIKit.

以下是apple.developer.com文档的链接.

  • Swift应该是`UIApplication.sharedApplication().idleTimerDisabled = true` (4认同)
  • Swift 3:`UIApplication.shared.idleTimerDisabled = true` (3认同)
  • 它改为```UIApplication.shared.isIdleTimerDisabled = true``` (2认同)

Cra*_*lot 17

对于Swift 3.0,这里有两个选项,具体取决于您要调用代码的位置:

在AppDelegate.swift内:

application.idleTimerDisabled = true

在AppDelegate.swift之外:

UIApplication.shared().isIdleTimerDisabled = true

  • 外部AppDelegate.swift代码应该是:`UIApplication.shared.isIdleTimerDisabled = false` (2认同)

kav*_*hmb 11

斯威夫特4

在AppDelegate.swift文件中,在应用程序函数中添加以下行:

    application.isIdleTimerDisabled = true
Run Code Online (Sandbox Code Playgroud)


小智 6

你可以使用我的小库Insomnia (Swift 3, iOS 9+) - 另一个不错的功能是你可以防止只有在充电时才睡觉。

idleTimerDisabledsoultion是好的,但你要记住将其设置为false之后。


leo*_*leo 5

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)