バッテリーの残量は、以下のようにすれば取得できます。ただし、iPhone4Sで検証したところ、0.05(5%)刻みのデータしか取得できませんでした。iPhone自体は最低でも1%刻みのデータを持っているはずなので非公開APIを使うなどすれば、より詳細なデータが取れるはずです。
残量を取得する
以下のようにすればバッテリーの残量を取得できます。
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
float batteryLevel = [UIDevice currentDevice].batteryLevel;
//バッテリー残量が変わったらbatteryLevelDidChangeにメッセージを送る
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(batteryLevelDidChange:)
name:UIDeviceBatteryLevelDidChangeNotification object:nil];
float batteryLevel = [UIDevice currentDevice].batteryLevel;
//バッテリー残量が変わったらbatteryLevelDidChangeにメッセージを送る
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(batteryLevelDidChange:)
name:UIDeviceBatteryLevelDidChangeNotification object:nil];
実行結果
2011-12-11 16:06:02.804 BatteryStatus[2004:707] -1.000000
2011-12-11 16:06:07.983 BatteryStatus[2004:707] 0.650000
2011-12-11 16:07:14.119 BatteryStatus[2004:707] -1.000000
2011-12-11 16:07:14.931 BatteryStatus[2004:707] 0.650000
2011-12-11 16:07:29.385 BatteryStatus[2004:707] 0.700000
2011-12-11 16:12:31.541 BatteryStatus[2004:707] 0.750000
2011-12-11 16:17:53.857 BatteryStatus[2004:707] 0.800000
2011-12-11 16:23:16.178 BatteryStatus[2004:707] 0.850000
2011-12-11 16:06:07.983 BatteryStatus[2004:707] 0.650000
2011-12-11 16:07:14.119 BatteryStatus[2004:707] -1.000000
2011-12-11 16:07:14.931 BatteryStatus[2004:707] 0.650000
2011-12-11 16:07:29.385 BatteryStatus[2004:707] 0.700000
2011-12-11 16:12:31.541 BatteryStatus[2004:707] 0.750000
2011-12-11 16:17:53.857 BatteryStatus[2004:707] 0.800000
2011-12-11 16:23:16.178 BatteryStatus[2004:707] 0.850000
充電ステータスを取得する
充電ステータスを取得するためには以下のように記述します。
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
[UIDevice currentDevice].batteryState;
//バッテリーの充電ステータスが変わったらbatteryLevelDidChangeにメッセージを送る
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(batteryStateDidChange:)
name:UIDeviceBatteryStateDidChangeNotification object:nil];
[UIDevice currentDevice].batteryState;
//バッテリーの充電ステータスが変わったらbatteryLevelDidChangeにメッセージを送る
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(batteryStateDidChange:)
name:UIDeviceBatteryStateDidChangeNotification object:nil];
取得される値は以下の4種類です。
バッテリー残量を活かしたアプリの例
『ざっくりバッテリー』
公式サンプルプログラム
BatteryStatus