2011-09-09 111 views
1

这是我简单的batteryLevel测试应用程序的简单代码。如何获得确切的电池电量?

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

这是我的应用程序的形象,希望你能看到状态栏电池电量和我的应用程序电量。我不知道为什么这些水平是不同的....? 一个是99%和应用程式水平是0.95这实际上是95%

enter image description here

回答

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) 

观察方法

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