开发者

How to get the exact battery level?

开发者 https://www.devze.com 2023-04-04 05:42 出处:网络
This is simple code of my simple batteryLevel Test app. - (void)viewDidLoad { [super viewDidLoad]; 开发者_开发问答UIDevice *device = [UIDevice currentDevice];

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%

How to get the exact battery level?


// 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)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消