检查电池电量iOS Swift

时间:2014-12-14 23:50:53

标签: ios swift

我刚开始使用Swift,我一直在寻找一种检查电池电量的方法。我发现this resource并且一直在玩它,但由于某种原因似乎无法让它发挥作用。

我不太确定如何解决这个问题。有什么想法吗?

2 个答案:

答案 0 :(得分:87)

首先启用电池监控:

UIDevice.current.isBatteryMonitoringEnabled = true

然后你可以创建一个计算属性来返回电池电量:

var batteryLevel: Float {
    return UIDevice.current.batteryLevel
}

要监控设备电池电量,您可以为UIDevice.batteryLevelDidChangeNotification添加观察者:

// Swift 4.1 or earlier
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: .UIDeviceBatteryLevelDidChange, object: nil)
// Swift 4.2 or later
// NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: UIDevice.batteryLevelDidChangeNotification, object: nil)

func batteryLevelDidChange(_ notification: Notification) {
    print(batteryLevel)
}

您还可以验证电池状态:

// Swift 4.1 or earlier
var batteryState: UIDeviceBatteryState {
    return UIDevice.current.batteryState
}
// Swift 4.2 or later
var batteryState: UIDevice.BatteryState {
    return UIDevice.current.batteryState
}

case .unknown   //  "The battery state for the device cannot be determined."
case .unplugged //  "The device is not plugged into power; the battery is discharging"
case .charging  //  "The device is plugged into power and the battery is less than 100% charged."
case .full      //   "The device is plugged into power and the battery is 100% charged."

并添加UIDevice.batteryStateDidChangeNotification的观察者:

// Swift 4.1 or earlier
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: .UIDeviceBatteryStateDidChange, object: nil)
// Swift 4.2 or later
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: UIDevice.batteryStateDidChangeNotification, object: nil)

func batteryStateDidChange(_ notification: Notification) {
    switch batteryState {
    case .unplugged, .unknown:
        print("not charging")
    case .charging, .full:
        print("charging or full")
    }
}

答案 1 :(得分:-1)

  

var batteryLevel:Float {get}

确保首先启用电池监控=)

Apple Documentation