我刚启动Swift,一直在寻找一种检查电池电量的方法。我找到了该资源并一直在使用它,但是由于某种原因似乎无法使它正常工作。
我不太确定如何解决此问题。有任何想法吗?
Xcode 11•Swift 5.1
首先只需启用电池监控:
UIDevice.current.isBatteryMonitoringEnabled = true
然后,您可以创建一个计算属性以返回电池电量:
电池电量从0.0(完全放电)到1.0(100%充电)。访问此属性之前,请确保已启用电池监视。如果未启用电池监视,则电池状态为UIDevice.BatteryState.unknown,此属性的值为–1.0。
var batteryLevel: Float { UIDevice.current.batteryLevel }
要监视设备的电池电量,您可以添加观察者 UIDevice.batteryLevelDidChangeNotification:
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:
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") } }