I am trying to display the iPhone's remaining battery level on a label in my apple watch app. I've tried using WatchConnectivity and sending messages between iphone and Apple Watch, but didn't work. Is there any way I can do it?
First just enable battery monitoring:
UIDevice.current.isBatteryMonitoringEnabled = true
Then you can create a computed property to return the battery level:
var batteryLevel: Float {
return UIDevice.current.batteryLevel
}
To monitor your device battery level you can add an observer for the UIDeviceBatteryLevelDidChange
notification:
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: .UIDeviceBatteryLevelDidChange, object: nil)
func batteryLevelDidChange(_ notification: Notification) {
print(batteryLevel)
}
You can also verify the battery state:
var batteryState: UIDeviceBatteryState {
return 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."
and add an observer for UIDeviceBatteryStateDidChange
notification:
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: .UIDeviceBatteryStateDidChange, object: nil)
func batteryStateDidChange(_ notification: Notification) {
switch batteryState {
case .unplugged, .unknown:
print("not charging")
case .charging, .full:
print("charging or full")
}
}
Now you have all the properties you need regarding your battery. Just pass them to the watch!
Hope this helps.