如何使用swift监控电池电量和状态变化

jam*_*n34 10 ios swift

所以,我正在试图弄清楚如何监控iOS设备中的电池电量和状态变化.

到目前为止,我已经确定了如何获得当前的电池电量,但无法弄清楚如何获得状态或如何监控任何更改,所以我可以弹出一个对话框(或通知,但我想我无法监控这个在背景中无论如何......)当100%充电时.

这是我到目前为止:

@IBOutlet var BatteryLevelLabel: UILabel!
@IBOutlet var BatteryStateLabel: UILabel!

// function to return the devices battery level
    func batteryLevel()-> Float {
        return UIDevice.currentDevice().batteryLevel
    }

// function to return the devices battery state (Unknown, Unplugged, Charging, or Full)
    func batteryState()-> UIDeviceBatteryState {
        return UIDevice.currentDevice().batteryState
    }

override func viewDidLoad() {
        super.viewDidLoad()

         let currentBatteryLevel = batteryLevel()

        // enables the tracking of the devices battery level
        UIDevice.currentDevice().batteryMonitoringEnabled = true

        // shows the battery level on labels
        BatteryLevelLabel.text = "\(batteryLevel() * 100)%)"
        BatteryStateLabel.text = "\(batteryState())"
        print("Device Battery Level is: \(batteryLevel()) and the state is \(batteryState())")

// shows alert when battery is 100% (1.0)
        if currentBatteryLevel == 1.0{
            let chargedAlert = UIAlertController(title: "Battery Charged", message: "Your battery is 100% charged.", preferredStyle: UIAlertControllerStyle.Alert)

            chargedAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
                print("Handle Ok logic here")
            }))
            presentViewController(chargedAlert, animated: true, completion: nil)
        }

    }
Run Code Online (Sandbox Code Playgroud)

这里的任何帮助将不胜感激!谢谢!

tba*_*nes 15

您可以使用电池状态通知,UIDeviceBatteryStateDidChangeNotificationUIDeviceBatteryLevelDidChangeNotification在状态发生变化时收到通知:

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryStateDidChange:", name: UIDeviceBatteryStateDidChangeNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryLevelDidChange:", name: UIDeviceBatteryLevelDidChangeNotification, object: nil)   

    // Stuff...
}

func batteryStateDidChange(notification: NSNotification){     
    // The stage did change: plugged, unplugged, full charge...
}

func batteryLevelDidChange(notification: NSNotification){     
   // The battery's level did change (98%, 99%, ...)
}
Run Code Online (Sandbox Code Playgroud)

  • 'UIDevice.currentDevice().batteryMonitoringEnabled = true'<br>应该在添加Observer之前.在swift 2中,只有在添加上述行后才会触发通知 (2认同)

KSi*_*att 5

这是实现为Swift 3.0建议的代码@tbaranes的新方法

NotificationCenter.default.addObserver(self, selector: Selector(("batteryStateDidChange:")), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: Selector(("batteryLevelDidChange:")), name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil)
Run Code Online (Sandbox Code Playgroud)