Is there a way to know when my device (iPhone) is plugged in to source power, like a computer or car audio systems with a USB port? I use localization services in my app and I want to change to kCLLocationAccuracyBestForNavigation
automatically when the device is plugged. Thanks...
You can enable battery monitoring thru the UIDevice class and check the battery state to see if it is being charged:
typedef enum {
UIDeviceBatteryStateUnknown,
UIDeviceBatteryStateUnplugged,
UIDeviceBatteryStateCharging,
UIDeviceBatteryStateFull,
} UIDeviceBatteryState;
You'll want to check for Charging or Full before enabling best GPS accuracy.
You can register to be notified when an accessory connects or disconnects.
Example:
[[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:@selector(accessoryDidConnect:)
name:EAAccessoryDidConnectNotification
object:nil];
[notificationCenter addObserver:self
selector:@selector(accessoryDidDisconnect:)
name:EAAccessoryDidDisconnectNotification
object:nil];
Once you receive this notification you can use a for loop to go through each accessory like:
NSArray *accessories = [[EAAccessoryManager sharedAccessoryManager] connectedAccessories];
EAAccessory *accessory = nil;
for (EAAccessory *obj in accessories)
{
// See if you're interested in this particular accessory
}
At some point (dealloc perhaps) you will want to unregister for these notifications. You can do this like:
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self
name:EAAccessoryDidDisconnectNotification
object:nil];
[notificationCenter removeObserver:self
name:EAAccessoryDidConnectNotification
object:nil];
[[EAAccessoryManager sharedAccessoryManager] unregisterForLocalNotifications];
To check the state of the battery:
UIDeviceBatteryState batteryState = [[UIDevice currentDevice] batteryState];
To subscribe to notifications about changes in the battery state, for instance by getting a call to your own action method batteryStateChanged
:
- (void) setup {
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
NSNotificationCenter * center= [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(batteryStateChanged)
name:UIDeviceBatteryStateDidChangeNotification
object:nil];
}
Remember to unsubscribe when your object is dealloced:
- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[UIDevice currentDevice] setBatteryMonitoringEnabled:NO];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With