gpt4 book ai didi

ios - isBatteryMonitoringEnabled 属性状态未变为 true

转载 作者:搜寻专家 更新时间:2023-10-31 23:09:14 29 4
gpt4 key购买 nike

我正在尝试制作一个简单的电池电量打印应用程序,但我无法将 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 作为输出(这意味着状态是未知)

如果有人帮助我解决我的问题,我将不胜感激!

最佳答案

在实际设备上运行时,以下内容对我有用。在应用程序委托(delegate)中,我启用了电池监控:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UIDevice.current.isBatteryMonitoringEnabled = true
return true
}

我有 View Controller,我可以在其中手动检查设备是否正在充电或在设备插入或拔出时接收通知。

类 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"
}
}

关于ios - isBatteryMonitoringEnabled 属性状态未变为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45399698/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com