ios - 检查电池电量 iOS Swift

标签 ios swift

<分区>

我刚开始使用 Swift,一直在寻找一种检查电池电量的方法。我找到了 this resource并且一直在玩弄它,但由于某种原因似乎无法让它工作。

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

最佳答案

Xcode 11 • Swift 5.1

首先启用电池监控:

UIDevice.current.isBatteryMonitoringEnabled = true

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

Battery level ranges from 0.0 (fully discharged) to 1.0 (100% charged). Before accessing this property, ensure that battery monitoring is enabled. If battery monitoring is not enabled, battery state is UIDevice.BatteryState.unknown and the value of this property is –1.0.

var batteryLevel: Float { UIDevice.current.batteryLevel }

要监控您的设备电池电量,您可以为 UIDevice.batteryLevelDidChangeNotification 添加观察者:

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

Battery level ranges from 0.0 (fully discharged) to 1.0 (100% charged). Before accessing this property, ensure that battery monitoring is enabled.
If battery monitoring is not enabled, battery state is UIDevice.BatteryState.unknown and the value of this property is –1.0.


@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 - 检查电池电量 iOS Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48384393/

相关文章:

ios - 在ios sdk中将标签文本显示为段落

swift - 如何制定描述字符串可表示枚举的协议(protocol)?

ios - 仅从存在用户 UID 的节点获取特定的子值

ios - 在任何 tableView 函数之外获取索引路径

iOS swift 如何将 imageview 准确地放置在 uiview 中

ios - 按排序顺序从日历 iphone 中获取所有事件的列表

ios - NSDateFormatter日期转换不正确

ios - 调用 `errno` 后测试 `strtol` 返回 "No such process"

ios - UITraitCollection getter,iOS13 不支持

ios - UITextView 表情符号字符限制计数不正确