I was trying to solve this question (the full code of the project is in that question) and I encountered an interesting problem, when I try to use UIDevice.current.batteryLevel
, it always returns -1.0
even though I set UIDevice.current.isBatteryMonitoringEnabled
to true
in Apple Docs, there's a definition that says it returns -1 if the battery monitoring is not enabled, but in my case it is enabled but it still returns -1
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.
Here's an example code:
struct ContentView: View {
init() {
UIDevice.current.isBatteryMonitoringEnabled = true
}
var body: some View {
VStack {
Text("Hello World")
}
.onAppear {
let batteryLevel = UIDevice.current.batteryLevel
print(batteryLevel)
}
}
}
Thanks in advance.