有没有returns"time until Device Battery is fully charged"的函数

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

我找到了显示电池百分比的答案 代码如下

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

问题在于剩余时间

提前致谢

UIDevice 没有内置函数。您所能做的就是检查 batteryState,当它是 charging 时,测量 UIDeviceBatteryLevelDidChange 通知之间的时间以计算充电速度,并据此估算剩余充电时间。

但是,由于充电时间与电池百分比不成正比,这种方法将非常不准确。

您可以尝试测量一段时间内的电池电量并自行计算

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
}

请注意,这样的估计不会很准确。

我没试过但是get clue from this question/answer and convert to Swift.

您可以在 ViewWillAppear/ViewDidLoad 中使用以下 NSNotificationCenter

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

每次在代码下方调用 cad 时都会通知您。

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
}

用户这可能对您的情况有所帮助。

是的,不要忘记删除 NSNotificationCenter"viewWillDisAppear"

中观察