Как будто вы пытаетесь получить доступ к объекту, который является null
. Рассмотрим ниже пример:
TypeA objA;
. В это время вы только что объявили этот объект, но не инициализировали или не инициализировали. И всякий раз, когда вы пытаетесь получить доступ к каким-либо свойствам или методам в нем, он будет генерировать NullPointerException
, что имеет смысл.
См. Также этот пример:
String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
Сначала просто включите мониторинг батареи:
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")
}
}
var batteryLevel: Float {get}
Убедитесь, что мониторинг батареи включен первым =)