4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-05-21

Swift4

Swift4.swift

import UIKit

/**
 * BatteryViewController.swift
 * バッテリーレベル / バッテリーステータスを表示するビューコントローラークラス
 **/
class BatteryViewController: UIViewController {
    // バッテリーレベルのラベル
    @IBOutlet weak var labelBatteryLevel: UILabel!
    // バッテリーステータスのラベル
    @IBOutlet weak var labelBatteryStatus: UILabel!
}

extension BatteryViewController {
    // 初期設定
    override func viewDidLoad() {
        super.viewDidLoad()
        // バッテリーの監視を開始
        startBatteryMonitoring()
        // バッテリー残量の変化に対する処理
        displayBatteryLevel()
     // バッテリーの給電状況の変化に対する処理
        displayBatteryState()
    }
}

バッテリーの状態を監視する方法 (iOS & Swift)

バッテリーの状態の監視を開始

Swift4.swift
extension BatteryViewController {
    func startBatteryMonitoring() {
        UIDevice.current.isBatteryMonitoringEnabled = true
        // バッテリー残量の変化を監視
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(BatteryViewController.batteryLevelChanged(notification:)),
            name: UIDevice.batteryLevelDidChangeNotification, object: nil)
        // バッテリー給電状況の変化を監視
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(ViewController.batteryStateChanged(notification:)),
            name: UIDevice.batteryStateDidChangeNotification, object: nil)
    }
}

バッテリー残量の変化に対する通知設定の処理

Swift4.swift
extension BatteryViewController {
    @objc func batteryLevelChanged(notification: Notification) {
        // バッテリー残量の変化に対するメソッド
        displayBatteryLevel()
    }
}

バッテリーの給電状況の変化に対する通知設定の処理

Swift4.swift
extension BatteryViewController {
    @objc func batteryStateChanged(notification: Notification) {
        displayBatteryState()
    }
}

バッテリー残量の変化に対する処理

Swift4.swift
extension BatteryViewController {

    func displayBatteryLevel() {
        // バッテリーのモニタリングをenableにする
        UIDevice.current.isBatteryMonitoringEnabled = true
        
        // Battery Lebelの初期値
        let bLevel:Float = UIDevice.current.batteryLevel
        
        if bLevel == -1 {
            // バッテリーレベルがモニターできないケース
            labelBatteryLevel.text = "バッテリーモニターNG"
        } else {
            labelBatteryLevel.text = "バッテリーレベル:  \(bLevel * 100) %"
        }
    }
}

バッテリーの給電状況の変化に対する処理

Swift4.swift
extension BatteryViewController {

    func displayBatteryState() {
        
        // Battery Statusの初期値
        var state:String = "バッテリーステータス: "
        
        switch UIDevice.current.batteryState {
        case .unplugged:
            state += "Unplugged"
        case .charging:
            state += "Charging"
        case .full:
            state += "full"
        case .unknown:
            state += "Unknown"
        }
        
        labelBatteryStatus.text = state
    }
}

バッテリーの状態を監視を終了

Swift4.swift
extension BatteryViewController {

    func stopBatteryMonitoring() {
        UIDevice.current.isBatteryMonitoringEnabled = false
        NotificationCenter.default.removeObserver(
            self,
            name: UIDevice.batteryLevelDidChangeNotification, object: nil)
        NotificationCenter.default.removeObserver(
            self,
            name: UIDevice.batteryStateDidChangeNotification, object: nil)
    }
}

QRコード
友達にも教えてね
65a9d2a3c00923a807192cc6a92ce94a.png


関連記事

【About】(http://qiita.com/sunstripe) - サンストライプ


制作チーム:サンストライプ

sunstripe_logo.png
http://sunstripe.main.jp/

(月1WEBコンテンツをリリースして便利な世の中を作っていくぞ!!ボランティアプログラマー/デザイナー/イラストレーター/その他クリエイター声優募集中!!)

地域情報 THEメディア

THE メディア 地域活性化をテーマに様々なリリース情報も含め、記事をお届けしてます!!
https://the.themedia.jp/

ゼロからはじめる演劇ワークショップ

多様化の時代に向けて他者理解を鍛える

プログラミングワークショップ・ウェブ塾の開講!!!

様々なテーマでプログラミングに囚われずに取り組んでいきます。
詳しくはこちら ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
プログラミングサロン 月1だけのプログラミング学習塾

協力応援 / 支援者の集い

チーム:サンストライプ

プログラミングラボ

一緒にポートフォリオを作りませんか?現場の体験やそれぞれの立場から年齢関係なく作品を作りたい方々と一緒にチームを作って、作品を作っています。現場に行きたい人には、職場紹介や職場の体験や悩み相談なども受けております。
様々な職種からプログラミングの知識を得たい、デザインの知識を得たい、データーベースの知識を得たいという人が集まっております。
週1のミーティングにそれぞれの近況と作業報告して、たまにリモート飲み会などをしております!!

興味がある方は、DMに話しかけてみてください。

トラストヒューマン

http://trusthuman.co.jp/
私たちは何よりも信頼、人と考えてます。

「コンサルティング」と「クリエイティブ」の両角度から「人材戦略パートナー」としてトータル的にサポートします!!

キャリア教育事業
広域学習支援プラットフォーム『のびのび日和』
https://slc-lab.amebaownd.com/

スポンサー募集

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?