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

标签 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)
        }

    }

如有任何帮助,我们将不胜感激!谢谢!

最佳答案

您可以使用电池状态通知 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%, ...)
}

关于ios - 如何使用swift监控电池电量和状态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31391373/

相关文章:

ios - 分段控制在分段 0 上未按预期工作

swift - 点击单元格中的按钮时如何获取 indexpath.row?

ios - 如何像Instagram那样在矩形中创建透明圆圈?

ios - 如何实现选择按钮

ios - 在 HTTP Post 上发送 NSDictionary 的格式是什么?

ios - 以编程方式全屏打开 iframe 视频

iOS - 以编程方式实现 SFGaugeView

ios - swift 2 : How to Load UITabBarController after Showing LoginViewController

ios - swift - iOS 9 : How do i present UIViewController with custom size in iOS 9?

swift - 创建后更改 UITextView 的 inputAccessoryView 中 UIBarButtonItem 的按钮标题?