首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何快速获取电池信息?

如何快速获取电池信息?
EN

Stack Overflow用户
提问于 2017-09-02 05:38:36
回答 2查看 3.9K关注 0票数 2

在我的项目中,我想详细显示电池信息。有了UIDevice,我可以很容易地获得电池的电量,但我的需求更多的就是这个。我想获得这样的电池健康,循环计数,电压和电池的更多细节。(越多越好!!)我真的需要一些建议,谢谢!

EN

回答 2

Stack Overflow用户

发布于 2017-09-02 05:42:25

正如您所指出的,UIDevice所提供的所有级别以及它的当前状态 (见下文)。您感兴趣的其他项目要么需要使用私有API (这将导致应用程序从商店中被拒绝),要么根本无法通过任何API向您提供。

对于任何想从与电池相关的UIDevice中获得什么的人来说,这包括了官方的Apple:

  • var batteryLevel: CGFloat返回一个从0.0 (空)到1.0 (完整)的值
  • var isBatteryMonitoringEnabled: Bool返回truefalse,这取决于您是否希望得到电池状态更改的通知。将其设置为true允许您获得batteryState
  • var batteryState: UIDeviceBatteryState提供电池状态,如果isBatteryMonitoringEnabled设置为false,则为unknown

可能的状态是:

unknown -无法确定设备的电池状态。

unplugged -该设备没有插入电源,电池正在放电。

charging -该设备是插入电源和电池不到100%充电。

full -该设备是插入电源和电池是100%充电。

票数 2
EN

Stack Overflow用户

发布于 2017-12-11 06:56:55

首先,只需启用电池监控:

代码语言:javascript
复制
UIDevice.current.isBatteryMonitoringEnabled = true

然后,您可以创建一个计算属性来返回电池级别:

代码语言:javascript
复制
var batteryLevel: Float {
    return UIDevice.current.batteryLevel
}

要监视设备的电池级别,可以为UIDeviceBatteryLevelDidChange通知添加一个观察者:

代码语言:javascript
复制
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: .UIDeviceBatteryLevelDidChange, object: nil)


func batteryLevelDidChange(_ notification: Notification) {
    print(batteryLevel)
}

您还可以验证电池状态:

代码语言:javascript
复制
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通知添加一个观察者:

代码语言:javascript
复制
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")
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46010819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档