33

I'm developing an music/video player app and just need to konw how to disable the auto-lock while my app is in foreground.

I know I've to use [[UIApplication sharedApplication] setIdleTimerDisabled:YES]; and [[UIApplication sharedApplication] setIdleTimerDisabled:NO]; at some point, but where is the best place to put them?

jMelnik
  • 1,055
  • 2
  • 15
  • 26

5 Answers5

26

Enable the idle timer in

- (void)applicationWillResignActive:(UIApplication *)application

and disable it in

- (void)applicationDidBecomeActive:(UIApplication *)application
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
10

The best place to disable it is in didFinishLaunchingWithOptions. The system will automatically take care of making the setting have no effect when the app is in the background.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    application.idleTimerDisabled = YES; 
    return YES;
}

I posted this alternative because the accepted answer does not prevent auto-lock when an alert appears (email, message, calendar event etc), or the notification center or control center is up.

malhal
  • 26,330
  • 7
  • 115
  • 133
7

Swift 3.0:

Inside AppDelegate.swift: application.idleTimerDisabled = true

Outside AppDelegate.swift: UIApplication.shared().isIdleTimerDisabled = true

Crashalot
  • 33,605
  • 61
  • 269
  • 439
3

And in Swift 3.0:

UIApplication.shared().isIdleTimerDisabled = true
Lukl
  • 41
  • 7
1

my 2 cents: for xcode 9:

 application.idleTimerDisabled = true

.....AppDelegate.swift:28:15: 'idleTimerDisabled' has been renamed to 'isIdleTimerDisabled'

so:

application.isIdleTimerDisabled = true
ingconti
  • 10,876
  • 3
  • 61
  • 48