バッテリー残量と状態を表示

2020/09/26確認

 f:id:fedora9:20200926121550p:plain

command + 1 して、Main.storyboardを選択して、画面を選択して、+をクリックして、Labelを2つ追加して、Editor - Assitantを選択して、右クリックで

class ViewController: UIViewController {

の下にラベルをドラッグして紐付けします。名前は、labelBatteryLevelとlabelBatteryStatus

  @IBOutlet weak var labelBatteryLevel: UILabel!

  @IBOutlet weak var labelBatteryStatus: UILabel!

が追加されます。

    super.viewDidLoad()

の下に、バッテリー残量と状態を表示する処理を追加します。

f:id:fedora9:20200926121836p:plain

[iPhone] Battery 電池残量を調べる

    // バッテリーのモニタリングをenableにする

    UIDevice.current.isBatteryMonitoringEnabled = true

 

    let bLevel:Float = UIDevice.current.batteryLevel

       

    if(bLevel == -1){

        // バッテリーレベルがモニターできないケース

        labelBatteryLevel.text = "Battery Level: ?"

    }

    else{

        labelBatteryLevel.text = "Battery Level:  \(bLevel * 100) %"

    }

       

    // Battery Status

    var state:String = "Battery Status: "

 

    if UIDevice.current.batteryState == UIDevice.BatteryState.unplugged {

           state += "Unplugged"

    }

 

    if UIDevice.current.batteryState == UIDevice.BatteryState.charging {

           state += "Charging"

    }

 

    if UIDevice.current.batteryState == UIDevice.BatteryState.full {

           state += "Full"

    }

 

    if UIDevice.current.batteryState == UIDevice.BatteryState.unknown {

           state += "Unknown"

    }

           

    labelBatteryStatus.text = state