我找到了显示电池百分比的答案 守则正在遵循
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.
}}
问题在于剩余时间
先谢谢
答案 0 :(得分:2)
UIDevice
没有内置功能。您只需检查batteryState
以及何时charging
,衡量计算充电速度的UIDeviceBatteryLevelDidChange
次通知与剩余充电时间之间的估算时间。
然而,由于充电时间与电池百分比不成正比,这种方法将非常不准确。
答案 1 :(得分:0)
您可以尝试在一段时间内测量电池电量并自行计算
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
}
请注意,此类估算不会非常准确。
答案 2 :(得分:0)
我还没试过get clue from this question/answer and convert to Swift.
您可以在NSNotificationCenter
。{/ p>中的ViewWillAppear/ViewDidLoad
下方使用
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"
观察