0

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.

grandsirr
  • 584
  • 4
  • 19
  • Does this answer your question? [iOS Battery monitoring Swift](https://stackoverflow.com/questions/35991438/ios-battery-monitoring-swift) – David Ansermot Oct 27 '22 at 15:50
  • https://stackoverflow.com/questions/35991438/ios-battery-monitoring-swift is this helping ? – David Ansermot Oct 27 '22 at 15:51
  • I don't think these questions contain any answers, also in that question the one who asked the question also says that it most of the time happens with physical devices too. – grandsirr Oct 27 '22 at 15:54
  • so I don't think these links are helpful @DavidAnsermot – grandsirr Oct 27 '22 at 15:54
  • Check the value of UIDevice.current.isBatteryMonitoringEnabled after you set it to true. On the sim it's not supported - you'll see it remains false, as this answer says: https://stackoverflow.com/questions/35991438/ios-battery-monitoring-swift – Shadowrun Oct 27 '22 at 16:17
  • @Shadowrun I also plugged my iphone 11 and it still returns false. – grandsirr Oct 27 '22 at 16:20
  • This isn't a valid question, downvoted. – SLE Dec 03 '22 at 16:15

0 Answers0