检查电池电量iOS Swift [英] Check Battery Level iOS Swift

查看:569
本文介绍了检查电池电量iOS Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用Swift,我一直在寻找一种检查电池电量的方法。我发现这个资源,并一直在玩它但由于某种原因似乎无法让它工作。

I just started Swift and I have been looking for a way to check the battery level. I found this resource and have been playing around with it but for some reason can't seem to get it to work.

我不是很确定如何解决这个问题。有什么想法?

I wasn't quite sure how to go about fixing this. Any ideas?

推荐答案

首先启用电池监控:

UIDevice.current.isBatteryMonitoringEnabled = true

然后你可以创建一个计算机返回电池级别的属性:

Then you can create a computed property to return the battery level:

var batteryLevel: Float {
    return UIDevice.current.batteryLevel
}

要监控设备电池电量,您可以为UIDeviceBatteryLevelDidChange通知添加观察者:

To monitor your device battery level you can add an observer for the UIDeviceBatteryLevelDidChange notification:

NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: .UIDeviceBatteryLevelDidChange, object: nil)







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

您还可以验证电池状态:

You can also verify the battery state:

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通知添加一个观察者:


and add an observer for UIDeviceBatteryStateDidChange notification:

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

这篇关于检查电池电量iOS Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆