nc

Disable auto-lock on the iPhone when plugged in

There are certain scenarios where it would be really useful to have the iPhone automatically disable the auto-lock. For example, when using a turn-by-turn navigation application, or when reading an ebook. It’s actually very simple to prevent the screen from locking in your iPhone application. You just need to call this one line of code:

[UIApplication sharedApplication].idleTimerDisabled = YES;

From the selection of applications I regularly use, one scenario is poorly catered: using the iPhone as an auxiliary display. Not necessary to display information directly from a connected Mac (i.e. an auxiliary external display), but a way of display information streams from news sites, social networks, and such like.

For example, wouldn’t it be great if you could use your iPhone as the primary display for your Twitter stream while it is plugged in? Let’s take Twitterrific 2.0 as an example. It has an option that will automatically refresh the active timeline at predefined interval (I’m not sure about the other Twitter clients available for the iPhone, but I know Tweetie does not have this option). However, even if you have your iPhone is plugged in, the auto-lock will still kick in after a couple of minutes. Frustrating, right? Let’s see how we can improve the user experience in our apps when the iPhone is plugged in.

This scenario can broken down into two parts: determining whether the device is connected or not to a power source; and detecting when this changes. As of iPhone OS 3.0, both of these tasks are straight-forward to implement.

Determining whether the iPhone (or indeed, the iPod Touch), is connected to a power source can be done by using the new-to-3.0 battery monitoring properties of the UIDevice class. First, you have to enable battery monitoring by setting the batteryMonitoringEnabled property to YES and then you can query the batteryState property. If it is either UIDeviceBatteryStateCharging or UIDeviceBatteryStateFull, you know the device is plugged in. For example:

UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = YES;
if (device.batteryState == UIDeviceBatteryStateCharging || 
    device.batteryState == UIDeviceBatteryStateFull) {
    // The device is plugged in
}
device.batteryMonitoringEnabled = NO;

Detecting when the power state changes involves registering a selector for the UIDeviceBatteryStateDidChangeNotification:

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

I’ve uploaded a sample application that demonstrates these three techniques to GitHub.