检查电池电量 iOS Swift
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27475506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check Battery Level iOS Swift
提问by B3TA
I just started Swift and I have been looking for a way to check the battery level. I found this resourceand have been playing around with it but for some reason can't seem to get it to work.
我刚刚开始使用 Swift,我一直在寻找一种检查电池电量的方法。我找到了这个资源并一直在玩它,但由于某种原因似乎无法让它工作。
I wasn't quite sure how to go about fixing this. Any ideas?
我不太确定如何解决这个问题。有任何想法吗?
回答by Leo Dabus
Xcode 11 ? Swift 5.1
Xcode 11?斯威夫特 5.1
First just enable battery monitoring:
首先启用电池监控:
UIDevice.current.isBatteryMonitoringEnabled = true
Then you can create a computed property to return the battery level:
然后你可以创建一个计算属性来返回电池电量:
Battery level ranges from 0.0 (fully discharged) to 1.0 (100% charged). Before accessing this property, ensure that battery monitoring is enabled. If battery monitoring is not enabled, battery state is UIDevice.BatteryState.unknown and the value of this property is –1.0.
电池电量范围从 0.0(完全放电)到 1.0(100% 充电)。在访问此属性之前,请确保已启用电池监控。如果未启用电池监控,则电池状态为 UIDevice.BatteryState.unknown,此属性的值为 –1.0。
var batteryLevel: Float { UIDevice.current.batteryLevel }
To monitor your device battery level you can add an observer for the UIDevice.batteryLevelDidChangeNotification
:
要监控您的设备电池电量,您可以添加一个观察者 UIDevice.batteryLevelDidChangeNotification
:
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
@objc func batteryLevelDidChange(_ notification: Notification) {
print(batteryLevel)
}
You can also verify the battery state:
您还可以验证电池状态:
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."
and add an observer for 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")
}
}
回答by Todd Perkins
var batteryLevel: Float { get }
var batteryLevel: Float { get }
Make sure that battery monitoring is enabled first =)
确保首先启用电池监控 =)