How to disable iPhone/iPad auto-lock while app is in foreground mode?

21.5k Views Asked by At

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?

5

There are 5 best solutions below

5
AudioBubble On BEST ANSWER

Enable the idle timer in

- (void)applicationWillResignActive:(UIApplication *)application

and disable it in

- (void)applicationDidBecomeActive:(UIApplication *)application
2
malhal On

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.

0
Lukl On

And in Swift 3.0:

UIApplication.shared().isIdleTimerDisabled = true
0
Crashalot On

Swift 3.0:

Inside AppDelegate.swift: application.idleTimerDisabled = true

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

0
ingconti On

my 2 cents: for xcode 9:

 application.idleTimerDisabled = true

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

so:

application.isIdleTimerDisabled = true