0

I have found an answer to display battery percentage The Code is Following

class ViewController: UIViewController {

@IBOutlet var infoLabel: UILabel!

var batteryLevel: Float {
    return UIDevice.current.batteryLevel
}
var timer = Timer()

func scheduledTimerWithTimeInterval(){
    timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(self.someFunction), userInfo: nil, repeats: true)
}
func someFunction() {

    self.infoLabel.text = String(format: "%.0f%%", batteryLevel * 100)
        }
override func viewDidLoad() {
    super.viewDidLoad()
    UIDevice.current.isBatteryMonitoringEnabled = true
    someFunction()
    scheduledTimerWithTimeInterval()
    // Do any additional setup after loading the view, typically from a nib.
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}}

The Problem is with the Remaining time

Thanks in Advance

Abhirajsinh Thakore
  • 1,806
  • 2
  • 13
  • 23
  • 2
    If `UIDevice.current.batteryState == .charging` then you can estimate this by measuring the battery level over a period of time - when you know the rate at which battery charges and remaining percentage, it's a matter of simple calculation. Note that this estimate will probably not be very accurate. – mag_zbc Jul 25 '17 at 11:37
  • @mag_zbc I am New to swift. Can u Explain that in detail or if possible can u provide me a demo or source code of that. – Abhirajsinh Thakore Jul 25 '17 at 11:39
  • @mag_zbc, I'm guessing Apple's estimate (on the Macs for instance) is pretty inaccurate too, and most likely relies on the same strategy. – LinusGeffarth Jul 25 '17 at 11:40
  • @LinusGeffarth Apple might be using some private APIs to help with calculating this and by using Machine Learning you can also improve this estimate quite a bit. The _remaining time estimate_ on `macOS ` is actually quite accurate. – Dávid Pásztor Jul 25 '17 at 12:40

3 Answers3

2

UIDevice has no built in function for this. All you can do is to check the batteryState and when it is charging, measure the time between UIDeviceBatteryLevelDidChange notifications to calculate the charging speed and from that estimate the remaining charging time.

However, this approach will be quite inaccurate due to the fact that charging time is not directly proportional to battery percentage.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
1

I haven't tried but get clue from this question/answer and convert to Swift.

You can use below NSNotificationCenter in your ViewWillAppear/ViewDidLoad.

NotificationCenter.default.addObserver(self, selector: #selector(self.batteryCharged), name: UIDeviceBatteryLevelDidChangeNotification, object: nil)

That will notify you every time cad will be called below code.

func batteryCharged() {
    let currBatteryLev: Float = UIDevice.currentDevice.batteryLevel
        // calculate speed of chargement
    let avgChgSpeed: Float = (prevBatteryLev - currBatteryLev) / startDate.timeIntervalSinceNow
        // get how much the battery needs to be charged yet
    let remBatteryLev: Float = 1.0 - currBatteryLev
        // divide the two to obtain the remaining charge time
    let remSeconds: TimeInterval = remBatteryLev / avgChgSpeed
    // convert/format `remSeconds' as appropriate
}

user this might be helpful in your case.

And Yes don't forget to remove NSNotificationCenter observe in "viewWillDisAppear"

Govaadiyo
  • 5,644
  • 9
  • 43
  • 72
0

You can try to measure the battery level over a period of time and calculate this yourself

var batteryLevel : Float = 0.0
var timer = Timer()

override func viewDidAppear(_ animated: Bool) {
    if UIDevice.current.isBatteryMonitoringEnabled && UIDevice.current.batteryState == .charging {
        batteryLevel = UIDevice.current.batteryLevel
        // measure again in 1 minute
        timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(self.measureAgain), userInfo: nil, repeats: false)
    }
}

func measureAgain() {
    let batteryAfterInterval = UIDevice.current.batteryLevel

    // calculate the difference in battery levels over 1 minute
    let difference = batteryAfterInterval - self.batteryLevel

    let remainingPercentage = 100.0 - batteryAfterInterval

    let remainingTimeInMinutes = remainingPercentage / difference
}

Note that such estimate will not be very accurate.

mag_zbc
  • 6,801
  • 14
  • 40
  • 62