How to get the exact battery level?

a 夏天 提交于 2019-12-13 00:35:59

问题


This is simple code of my simple batteryLevel Test app.

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;
    mLabel.text = [NSString stringWithFormat:@"%0.5f",device.batteryLevel];
}

This is the image of my app, hope you can see the status bar battery level and my application battery level. I don't know why these levels are different....? one is 99% and apps level is 0.95 which is actually 95%


回答1:


// Enable this property
UIDevice.current.isBatteryMonitoringEnabled = true

// Then add observer
NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange(notification:)), name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil)

Observer method

@objc func batteryLevelDidChange(notification: NSNotification) {
  // The battery's level did change
  print(UIDevice.current.batteryLevel)
}


来源:https://stackoverflow.com/questions/7360400/how-to-get-the-exact-battery-level

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!