5

I am making a GPS app and the accuracy changes based on if power is available (ie vehicle charger)

Is there a way to run something in the background that constantly checks to see if a device is receiving power?

I know how to check if power is connected. But the issue is IF the user is at home and connected. He unplugs the device to go out on a run. Then decides to hang out. My app checks the battery state on launch. How can I check it again and again. I don't want to drain his battery because he was using my app!

We plan on only supporting iOS 5 and higher (no need for backward compatibility with iOS 4 and 3)

Thanks

Abizern
  • 146,289
  • 39
  • 203
  • 257
Cocoa Dev
  • 9,361
  • 31
  • 109
  • 177
  • I rolled the question back because your edit radically changes it. If you have another question, please ask another question rather than radically changing an existing one. – Abizern Jul 05 '12 at 16:46

1 Answers1

20

Have a look at the UIDevice class reference.

There is a property called batteryState that returns a UIDeviceBatteryState. So, to see if the device is charging or is plugged in and full.

UIDeviceBatteryState currentState = [[UIDevice currentDevice] batteryState];
if (currentState == UIDeviceBatteryStateCharging || currentState == UIDeviceBatteryStateFull) {
    // The battery is either charging, or connected to a charger and is fully charged
}

Edited to add

If you want to continuously monitor the state, take a look at the batteryMonitoringEnabled property and then handle the UIDeviceBatteryStateDidChangeNotification to update whatever you want to.

iOS is event driven. Checking the state of something within a while loop is something you very rarely need to do.

Abizern
  • 146,289
  • 39
  • 203
  • 257
  • Do I run this in a while(true) loop? – Cocoa Dev Jul 05 '12 at 14:22
  • You could use notification center to send a notification when it is not charging and maybe pop up an alert. – pasawaya Jul 05 '12 at 14:28
  • i updated my code and provided it but it doesn't seem to work. – Cocoa Dev Jul 05 '12 at 16:42
  • 4
    Note that according to the [documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/doc/uid/TP40006902-CH3-SW21), the `batteryState` method will always just return `UIDeviceBatteryStateUnknown` unless you have set the [`batteryMonitoringEnabled` property](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/doc/uid/TP40006902-CH3-SW39) to `YES`. (That might be the issue you were running into @CocoaDev) – smileyborg Dec 28 '13 at 09:30