Reputation: 1701
How can I prevent screen lock only when using Navigation?
Waze has the option to do that, how can I do this in my App?
Upvotes: 147
Views: 69789
Reputation: 113
SwiftUI code:
import SwiftUI
import UIKit
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
}
}
}
Upvotes: 8
Reputation: 3722
Use this:
Objective-C:
[[UIApplication sharedApplication] setIdleTimerDisabled: YES];
Swift (legacy):
UIApplication.sharedApplication().idleTimerDisabled = true
Swift 3 and above:
UIApplication.shared.isIdleTimerDisabled = true
Make sure to import UIKit
.
Here is the link to the documentation from developer.apple.com.
Upvotes: 291
Reputation: 9913
Swift 4
in AppDelegate.swift file, add the following line inside application function:
application.isIdleTimerDisabled = true
Upvotes: 17
Reputation: 292
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).
Upvotes: 0
Reputation: 34523
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
Upvotes: 25