要解决这个问题,您需要在代码中将isBatteryMonitoringEnabled属性设置为true。以下是一个示例:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 将isBatteryMonitoringEnabled属性设置为true
UIDevice.current.isBatteryMonitoringEnabled = true
// 检查电池状态
let batteryLevel = UIDevice.current.batteryLevel
let batteryState = UIDevice.current.batteryState
print("Battery Level: \(batteryLevel)")
print("Battery State: \(batteryState.rawValue)")
}
}
在上述示例中,我们首先将isBatteryMonitoringEnabled属性设置为true,然后使用UIDevice.current.batteryLevel和UIDevice.current.batteryState来获取电池的电量和状态。请确保在使用这些属性之前将isBatteryMonitoringEnabled设置为true,以确保正确的电池信息。