Search code examples
swiftxcodeswift3xcode8uidevice

Is there any function which returns "time until Device Battery is fully charged"


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


Solution

  • 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.