How to get real time battery level on iOS with a 1% granularity

后端 未结 7 1697
清酒与你
清酒与你 2020-12-05 03:19

I\'m using this function to get current battery level of device:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
UIDevice *myDevice = [UIDevice c         


        
相关标签:
7条回答
  • 2020-12-05 03:52

    If you are using swift 5.1 or greater this code will definitely work for you.

    Step 1:- To get started, first enable the isBatteryMonitoringEnabled property of the current device, like this:-

    UIDevice.current.isBatteryMonitoringEnabled = true
    

    Step 2:- You can now read the current battery level

    let level = UIDevice.current.batteryLevel
    print(level)
    
    0 讨论(0)
  • 2020-12-05 03:53
    UIDevice *myDevice = [UIDevice currentDevice];    
    [myDevice setBatteryMonitoringEnabled:YES];
    
    double batLeft = (float)[myDevice batteryLevel] * 100;
    NSLog(@"%.f", batLeft);    
    
    NSString * levelLabel = [NSString stringWithFormat:@"%.f%%", batLeft];    
    lblLevel.text = levelLabel;
    
    0 讨论(0)
  • 2020-12-05 03:55

    The answers above are very good, but they are all in Obj-C, I have used these with other examples to do the same task on MonoTouch, so I am putting my code here in case anybody needs it:

    try
    {
        UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
        _Battery.Level = (int)(UIDevice.CurrentDevice.BatteryLevel * IOSBatteryLevelScalingFactor);
        _Battery.State = UIDevice.CurrentDevice.BatteryState;
    }
    catch (Exception e)
    {
        ExceptionHandler.HandleException(e, "BatteryState.Update");
        throw new BatteryUpdateException();
    }
    finally
    {
        UIDevice.CurrentDevice.BatteryMonitoringEnabled = false;
    }
    

    I also have a full post on my blog to give all the details in here

    0 讨论(0)
  • 2020-12-05 03:56

    Swift version to get the battery level:

    UIDevice.current.isBatteryMonitoringEnabled = true
    let batteryLevel = UIDevice.current.batteryLevel 
    

    batteryLevel return 0,39; 0,40 values for me.

    0 讨论(0)
  • 2020-12-05 04:02

    You can find a perfect answer here

    Xcode: 11.4 Swift: 5.2

    Click Here

    0 讨论(0)
  • 2020-12-05 04:06

    There are at least four different ways to read the battery level, and all four ways may return different values.

    Here is a chart of these values through time.

    The values were recorded with this iOS project: https://github.com/nst/BatteryChart

    Please check out the code for reference.

    iPhone 5 Battery

    0 讨论(0)
提交回复
热议问题