2016-12-13 53 views
1

我只是想編寫簡單的代碼,檢測何時iPhone被拔出,然後插入。但是事件驅動,而不是使用while循環。此代碼可以正常工作,但不檢測電話是否被拔出,並且不會更新打印的文本。檢測當iPhone被拔出並插入

編輯 從長遠來看,我只想讓手機在iPhone拔出時播放聲音。 (對不起,離開最終目標了。)。我正在使用這個打印語句,所以我可以確保它正在工作。

func startCharger() 
    { 

     printscreen.text="Started charger protocol" 

     UIDevice.current.isBatteryMonitoringEnabled=true 

     if(UIDevice.current.batteryState == .unplugged) 
     { 
      printscreen.text="Battery is unplugged" 
     } 
     else 
     { 
      printscreen.text="Battery is plugged in" 
     } 
    } 
+0

您需要使用通知中心,我相信。 https://developer.apple.com/reference/foundation/nsnotificationcenter – Ro4ch

+0

我也看到了,好的,我會代碼嗎?我剛剛開始與迅速今天大聲笑..所以我不完全理解語法。 –

+0

[如何知道iOS設備何時插入?](http://stackoverflow.com/questions/9300711/how-to-know-when-ios-device-is-plugged-in)可能的重複。使用KVO。 – JAL

回答

0

你可以在電池狀態變化的通知,UIDeviceBatteryStateDidChange,代碼看起來像這樣:

NotificationCenter.default.addObserver(
    self, 
    selector: #selector(batteryStateChanged), 
    name: .UIDeviceBatteryStateDidChange, 
    object: nil) 

當然,你需要在視圖控制器的方法(或任何你想要得到通知)。在這個例子中:

func batteryStateChanged(){ 
    // Your logic 
} 
+0

我會試試這個,從長遠來看,我希望它在播放時不會發出聲音。 –

0

快速實現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) 
}