Ответ 1
Сначала просто включите мониторинг батареи:
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)
@objc 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)
@objc func batteryStateDidChange(_ notification: Notification) {
switch batteryState {
case .unplugged, .unknown:
print("not charging")
case .charging, .full:
print("charging or full")
}
}