Ios BatteryMonitoringEnabled属性状态是否未变为true
我正在尝试制作一个简单的电池电量打印应用程序,但无法将Ios BatteryMonitoringEnabled属性状态是否未变为true,ios,swift,Ios,Swift,我正在尝试制作一个简单的电池电量打印应用程序,但无法将isBatteryMonitoringEnabled属性状态设置为true。我做了每一件事,但我没有做到 以下是我迄今为止所做的工作: import UIKit class ViewController: UIViewController { @IBAction func Start(_ sender: Any) { UIDevice.current.isBatteryMonitoringEnabled = tru
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作为输出(这意味着状态是未知的)
如果有人帮我解决问题,我将不胜感激 在实际设备上运行时,以下内容对我有效。在应用程序委托中,我启用电池监控:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UIDevice.current.isBatteryMonitoringEnabled = true
return true
}
我有一个View Controller,可以在其中手动检查设备是否正在充电,或者在设备插入或拔出时接收通知
类ViewController:UIViewController{
@IBOutlet弱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"
}
}
}模拟器没有电池。在真实设备上运行。即使在真实设备上运行,我也会遇到同样的问题。你找到解决办法了吗?