在我的项目中,我想详细显示电池信息。有了UIDevice,我可以很容易地获得电池的电量,但我的需求更多的就是这个。我想获得这样的电池健康,循环计数,电压和电池的更多细节。(越多越好!!)我真的需要一些建议,谢谢!
发布于 2017-09-02 05:42:25
正如您所指出的,UIDevice所提供的所有级别以及它的当前状态 (见下文)。您感兴趣的其他项目要么需要使用私有API (这将导致应用程序从商店中被拒绝),要么根本无法通过任何API向您提供。
对于任何想从与电池相关的UIDevice中获得什么的人来说,这包括了官方的Apple:
var batteryLevel: CGFloat返回一个从0.0 (空)到1.0 (完整)的值var isBatteryMonitoringEnabled: Bool返回true或false,这取决于您是否希望得到电池状态更改的通知。将其设置为true允许您获得batteryStatevar batteryState: UIDeviceBatteryState提供电池状态,如果isBatteryMonitoringEnabled设置为false,则为unknown。可能的状态是:
unknown -无法确定设备的电池状态。
unplugged -该设备没有插入电源,电池正在放电。
charging -该设备是插入电源和电池不到100%充电。
full -该设备是插入电源和电池是100%充电。
发布于 2017-12-11 06:56:55
首先,只需启用电池监控:
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")
}
}https://stackoverflow.com/questions/46010819
复制相似问题