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

5

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?

Daub answered 23/2, 2012 at 12:14 Comment(0)
U
26

Enable the idle timer in

- (void)applicationWillResignActive:(UIApplication *)application

and disable it in

- (void)applicationDidBecomeActive:(UIApplication *)application
Utopian answered 23/2, 2012 at 12:16 Comment(5)
It worked fine here but I'm wondering It'll work on dockstations and apple tv? Don't have any here to test.Daub
I've heard that another option is to play a silent "sound".Nims
@HotLicks that would probably result in your app getting rejected, but no one could say that for sure.Takamatsu
Actually this is quite nice hack. Thank you very much :)Sofer
This is not the correct place because when any alert appears, or the notification center or control center is up then the application resigns active and you risk the device auto-locking.Vincentvincenta
V
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.

Vincentvincenta answered 3/8, 2015 at 14:35 Comment(2)
what if an application in the background? whether the auto lock disabled in this situation?Chew
auto-lock is not disabled in the background, Apple don't allow it.Vincentvincenta
A
7

Swift 3.0:

Inside AppDelegate.swift: application.idleTimerDisabled = true

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

Achondroplasia answered 24/4, 2017 at 17:9 Comment(0)
Z
3

And in Swift 3.0:

UIApplication.shared().isIdleTimerDisabled = true
Zany answered 10/8, 2016 at 14:50 Comment(0)
W
1

my 2 cents: for xcode 9:

 application.idleTimerDisabled = true

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

so:

application.isIdleTimerDisabled = true
Watersoak answered 28/10, 2017 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.