您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

检查电池电量iOS Swift

检查电池电量iOS Swift

首先只需启用电池监控:

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")
    }
}
Swift 2022/1/1 18:20:22 有312人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶