大佬教程收集整理的这篇文章主要介绍了检查电池电量iOS Swift,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
首先只需启用电池监控:
UIDevice.current.isBatterymonitoringEnabled = true
然后,您可以创建一个计算属性以返回电池电量:
var batterylevel: float { UIDevice.current.batterylevel }
要监视设备的电池电量,您可以添加观察者 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
:
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")
}
}
以上是大佬教程为你收集整理的检查电池电量iOS Swift全部内容,希望文章能够帮你解决检查电池电量iOS Swift所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。