koogawa blog

iOS、Android、foursquareに関する話題

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

f:id:koogawa:20131205020919p:plain

iOSバイスのバッテリー残量、充電状態を取得できます。

実装方法

バッテリー残量は次のように取得できます。

Objective-C:

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 になります。

Objective-C:

device.batteryMonitoringEnabled = YES;

Swift:

UIDevice.currentDevice().batteryMonitoringEnabled = true

UIDeviceBatteryLevelDidChangeNotification を監視することで、バッテリー残量が変化した際に通知を受け取ることができます。

Objective-C:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(batteryLevelDidChange:)
                                             name:UIDeviceBatteryLevelDidChangeNotification
                                           object:nil];

Swift:

NSNotificationCenter.defaultCenter().addObserver(self,
    selector: "batteryLevelDidChange",
    name: UIDeviceBatteryLevelDidChangeNotification,
    object: nil)

バッテリーの充電状態も取得できます。

Objective-C:

UIDeviceBatteryState batteryState = device.batteryState;

Swift:

let status: UIDeviceBatteryState = UIDevice.currentDevice().batteryState

戻り値の持つ意味は次の通りです。

UIDeviceBatteryState 意味
UIDeviceBatteryStateFull フル充電
UIDeviceBatteryStateUnplugged 充電中ではない
UIDeviceBatteryStateCharging 充電中
UIDeviceBatteryStateUnknown 状態不明

UIDeviceBatteryStateDidChangeNotification を監視することで、バッテリーの充電状態が変化した際に通知を受け取ることができます。

Objective-C:

[[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などにシェアするアプリ(すでにある)
  • バッテリー残量と連動させたゲームアプリ

参考リンク