在iOS中,我們在任何時候都沒有像在Android中一樣的設備級訪問。我們的應用程序只能在未終止時接收電池狀態等通知。
當您的應用程序具有前景時,請嘗試使用下面的代碼來訪問設備的電池狀態。
// Begins battery state monitoring //
UIDevice.currentDevice().batteryMonitoringEnabled = true
// Check for battery's current status //
if (UIDevice.currentDevice().batteryState != .Unplugged) {
print("Device is plugged in.")
}
你也可以運行下面的代碼在設定的時間來檢查設備的電池狀態時,你的應用程序達到背景。 注 - 進行以下操作很可能會使您從App Store發行版中拒絕。
func applicationDidEnterBackground(application: UIApplication) {
// Begins battery state monitoring //
UIDevice.currentDevice().batteryMonitoringEnabled = true
// Schedules NSTimer with intervals of 10 seconds //
NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(batteryCheck), userInfo: nil, repeats: true)
}
func batteryCheck() {
if (UIDevice.currentDevice().batteryState != .Unplugged) {
print("Device is charging.")
} else {
print("Device is NOT charging.")
}
}