Сначала просто включите мониторинг батареи:
UIDevice.current.isBatteryMonitoringEnabled = true
Затем вы можете создать вычисленное свойство, чтобы вернуть уровень заряда батареи:
var batteryLevel: Float {
return UIDevice.current.batteryLevel
}
. Чтобы контролировать уровень заряда вашего устройства, вы можете добавьте наблюдателя для уведомления UIDeviceBatteryLevelDidChange:
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: .UIDeviceBatteryLevelDidChange, object: nil)
func batteryLevelDidChange(_ notification: Notification) {
print(batteryLevel)
}
Вы также можете проверить состояние батареи:
var batteryState: UIDeviceBatteryState {
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."
и добавьте наблюдателя для уведомления UIDeviceBatteryStateDidChange:
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: .UIDeviceBatteryStateDidChange, object: nil)
func batteryStateDidChange(_ notification: Notification) {
switch batteryState {
case .unplugged, .unknown:
print("not charging")
case .charging, .full:
print("charging or full")
}
}