Search code examples
iphoneiosobjective-cuideviceidle-timer

How to prevent iPhone to lock when my app is charging


Whole question is in title.
Here what I did.
I test it I plug iPhone to my mac not to charger I don;t know if this is important.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{...
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(batteryStateDidChange:)
                                                 name:UIDeviceBatteryStateDidChangeNotification object:nil];
...}

- (void)batteryStateDidChange:(NSNotification *)notification
{
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

    if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging ||
        [[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateFull ){

        [UIApplication sharedApplication].idleTimerDisabled = YES;
    }
    else if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateUnplugged) {

        [UIApplication sharedApplication].idleTimerDisabled = NO;
    }
}

What am I missing?


Solution

  • The immediate problem I see is that you're registering to be notified when the charging status changes in the future, but not configuring what to do with the idle timer before the state of the charger actually changes.

    For example, if you build to your device, it is plugged in and charging (possibly full) and unless you unplug your device, the UIDeviceBatteryStateDidChangeNotification has no reason to be posted.

    Consider something like this:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(batteryStateDidChange:)
                                                 name:UIDeviceBatteryStateDidChangeNotification object:nil];
    
    [self batteryStateDidChange:nil];