2011-09-09 72 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) 
}