swiftwatchkitbatterylevel

isBatteryMonitoringEnabled does not change value


I need to know the battery state in my watch app, but I can not set isBatteryMonitoringEnabled to true.

Is there anything else I should do beforehand? Or rules on where to change the property?


Solution

  • It looks like on watchOS and UIKit you could set up battery monitoring like so.

    @IBOutlet weak var battery: WKInterfaceLabel!
    
    @IBAction func getLevel() {
            let device = WKInterfaceDevice.current()
            device.isBatteryMonitoringEnabled = true
    
            let level = device.batteryLevel
    
            // Do something with the battery monitoring.
            print("Battery level is: \(level)")
            battery.setText("Level: \(level)")
        }
    

    On the watchOS simulator it appears battery level monitoring will always return a value of -1.0, you'll need to run this on an actual device.

    Here's a link to the documentation.