检查电池电量iOS Swift

我刚刚开始使用Swift,并一直在寻找一种方法来检查电池电量。 我发现这个资源 ,一直在玩它,但由于某种原因似乎无法得到它的工作。

我不太清楚如何去解决这个问题。 有任何想法吗?

首先启用电池监控:

UIDevice.current.isBatteryMonitoringEnabled = true 

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

 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) } 

您还可以validation电池状态:

 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}

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

Apple文档