简体   繁体   中英

isBatteryMonitoringEnabled property status not turning to true

I am trying to make a simple battery level printing app but I am not able to turn the isBatteryMonitoringEnabled property status to true . I have done every thing but I failed to do so.

So here is what I have done so far:

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

Whenever I compiled and run this code on a Simulator, I always get -1.0 as an output (Which means that status is unknown )

I would highly appreciate if someone help me to solve my problem!

The following works for me when running on an an actual device. In the application delegate I enable battery monitoring:

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

I have View Controller where I can manually check if the device is charging or receive notifications when the device is plugged or unplugged.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM