快速實現Dule的代碼。 檢查電源是否連接。 將這些功能複製到您的班級中。 呼叫isPowerConnected()在viewDidLoad中
func isPowerConnected(){
UIDevice.current.isBatteryMonitoringEnabled = true
NotificationCenter.default.addObserver(
self,
selector: #selector(batteryStateChanged),
name: .UIDeviceBatteryStateDidChange,
object: nil)
}
var chargingVar = "" //Empty Variable
func batteryStateChanged(){
if (UIDevice.current.batteryState == .charging) { //Here we check if the device is charging
UIApplication.shared.isIdleTimerDisabled = true //Here we disable the lock screen time out value
self.chargingVar = "is charging. \u{1F603}" //Here we change the variable to "is charging"
chargingAlaer() //If power is pluged in we send an Alert
}else{
self.chargingVar = "is not charging. \u{1F622} " //Here we change the variable to "is not charging"
chargingAlaer() //If power is not pluged we send an Alert
}
}
func chargingAlaer(){
let alertController = UIAlertController(title: "Charging Status",
message: "Your device \(chargingVar)",
preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK",
style: UIAlertActionStyle.default,
handler: {(action) -> Void in
})
alertController.addAction(ok)
self.present(alertController, animated: true, completion: nil)
}
您需要使用通知中心,我相信。 https://developer.apple.com/reference/foundation/nsnotificationcenter – Ro4ch
我也看到了,好的,我會代碼嗎?我剛剛開始與迅速今天大聲笑..所以我不完全理解語法。 –
[如何知道iOS設備何時插入?](http://stackoverflow.com/questions/9300711/how-to-know-when-ios-device-is-plugged-in)可能的重複。使用KVO。 – JAL