【Tips】iOSデバイスのバッテリー残量を取得する(Swift対応)

実装方法
バッテリー残量は次のように取得できます。
float batteryLevel = [UIDevice currentDevice].batteryLevel;
Swift:
let batteryLevel: Float = UIDevice.currentDevice().batteryLevel
戻り値として、0.0〜1.0 の値が 0.05 刻みで返ってきます。数値が大きいほどバッテリーの残量も大きくなります。残量が取得できない場合は -1.0 が返ります。
バッテリー残量を取得するには、batteryMonitoringEnabled プロパティを YES に設定します。こうしないと、batteryLevel の値は常に -1.0 になります。
device.batteryMonitoringEnabled = YES;
Swift:
UIDevice.currentDevice().batteryMonitoringEnabled = true
UIDeviceBatteryLevelDidChangeNotification を監視することで、バッテリー残量が変化した際に通知を受け取ることができます。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelDidChange:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
Swift:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryLevelDidChange", name: UIDeviceBatteryLevelDidChangeNotification, object: nil)
バッテリーの充電状態も取得できます。
UIDeviceBatteryState batteryState = device.batteryState;
Swift:
let status: UIDeviceBatteryState = UIDevice.currentDevice().batteryState
戻り値の持つ意味は次の通りです。
| UIDeviceBatteryState | 意味 |
|---|---|
| UIDeviceBatteryStateFull | フル充電 |
| UIDeviceBatteryStateUnplugged | 充電中ではない |
| UIDeviceBatteryStateCharging | 充電中 |
| UIDeviceBatteryStateUnknown | 状態不明 |
UIDeviceBatteryStateDidChangeNotification を監視することで、バッテリーの充電状態が変化した際に通知を受け取ることができます。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStateDidChange:) name:UIDeviceBatteryStateDidChangeNotification object:nil];
Swift:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryStateDidChange", name: UIDeviceBatteryStateDidChangeNotification, object: nil) }
バッテリー状況の取得が不要になったら、batteryMonitoringEnabled プロパティを NO に設定しておきましょう。
サンプルコード
注意点
- (当たり前ですが)シミュレータ上ではバッテリー残量が取得できません
作れそうなアプリ
- バッテリー残量をSNSなどにシェアするアプリ(すでにある)
- バッテリー残量と連動させたゲームアプリ