[英]isBatteryMonitoringEnabled property status not turning to true
我正在尝试制作一个简单的电池级打印应用程序,但我无法将isBatteryMonitoringEnabled
属性状态变为true
。 我已经完成了所有事情,但我没有这样做。
所以这就是我到目前为止所做的:
import UIKit
class ViewController: UIViewController {
@IBAction func Start(_ sender: Any) {
UIDevice.current.isBatteryMonitoringEnabled = true
var batteryLevel: Float {
return UIDevice.current.batteryLevel
}
print(batteryLevel)
}
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
}
每当我在模拟器上编译并运行此代码时,我总是得到-1.0作为输出(这意味着状态unknown
)
如果有人帮我解决我的问题,我将非常感激!
在实际设备上运行时,以下内容适用于我。 在应用程序委托中,我启用了电池监控:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UIDevice.current.isBatteryMonitoringEnabled = true
return true
}
我有View Controller,我可以在设备插入或拔出时手动检查设备是否正在充电或接收通知。
class ViewController:UIViewController {@IBOutlet weak var chargingLabel:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateChanged(_:)), name: UIDevice.batteryStateDidChangeNotification, object: nil)
updateBatteryUI()
}
@objc func batteryStateChanged(_ notification:Notification) {
if UIDevice.current.batteryState == .charging {
UIApplication.shared.isIdleTimerDisabled = true
chargingLabel.text = "Charging"
} else {
chargingLabel.text = "Not Charging"
}
}
func updateBatteryUI() {
if UIDevice.current.batteryState == .charging {
UIApplication.shared.isIdleTimerDisabled = true
chargingLabel.text = "Charging"
} else {
chargingLabel.text = "Not Charging"
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.