栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

检查电池电量iOS Swift

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

检查电池电量iOS Swift

Xpre 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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/370386.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号