首先只需启用电池监控:
UIDevice.current.isBatteryMonitoringEnabled = true
电池电量从0.0(完全放电)到1.0(100%充电)。访问此属性之前,请确保已启用电池监视。如果未启用电池监视,则电池状态为UIDevice.BatteryState.unkNown,此属性的值为–1.0。
var batteryLevel: Float { UIDevice.current.batteryLevel }
要监视设备的电池电量,您可以添加观察者 UIDevice.batteryLevelDidChangeNotification
:
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
@objc func batteryLevelDidChange(_ notification: Notification) {
print(batteryLevel)
}
您还可以验证电池状态:
var batteryState: UIDevice.BatteryState { 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
:
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: UIDevice.batteryStateDidChangeNotification, object: nil)
@objc func batteryStateDidChange(_ notification: Notification) {
switch batteryState {
case .unplugged, .unkNown:
print("not charging")
case .charging, .full:
print("charging or full")
}
}