检查电池电量iOS Swift

B3T*_*3TA 23 ios swift

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

我不太确定如何解决这个问题.有任何想法吗?

Leo*_*bus 101

首先启用电池监控:

UIDevice.current.isBatteryMonitoringEnabled = true
Run Code Online (Sandbox Code Playgroud)

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

var batteryLevel: Float { UIDevice.current.batteryLevel }
Run Code Online (Sandbox Code Playgroud)

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

NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)
@objc func batteryLevelDidChange(_ notification: Notification) {
    print(batteryLevel)
}
Run Code Online (Sandbox Code Playgroud)

您还可以验证电池状态:

var batteryState: UIDevice.BatteryState { UIDevice.current.batteryState }
Run Code Online (Sandbox Code Playgroud)
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."
Run Code Online (Sandbox Code Playgroud)

并添加一个观察者UIDevice.batteryStateDidChangeNotification:

NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: UIDevice.batteryStateDidChangeNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)
@objc func batteryStateDidChange(_ notification: Notification) {
    switch batteryState {
    case .unplugged, .unknown:
        print("not charging")
    case .charging, .full:
        print("charging or full")
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不适合我的情况.始终接收-1.0 (4认同)
  • 非常感谢这正是我想要的 (2认同)