2017-09-07 23 views
0

デバイスの充電ポートが正常に動作しているかどうかを確認しようとしています。 2つのシナリオがあります: a。充電ケーブルがすでに差し込まれているとき。 b。いつでも充電ケーブルを差し込んでください。uidevicebatterystatedidchangenotificationが動作しない場合がある

ケースaの場合は、viewDidLoad()を確認し、有効なbatteryStateMonitoringを確認して、バッテリーの現在の状態を確認しました。 - それはいつも動く。

は、ケースBの場合、私はNSNotification S UIDeviceBatteryStateDidChangeNotification

 override func viewDidLoad() { 
     UIDevice.current.isBatteryMonitoringEnabled = true 
     self.checkForCharging() 
    } 

func checkForCharging() { 
if UIDevice.current.batteryState == .full || UIDevice.current.batteryState == .charging { 
      self.updateUIForChargingTest() 
     } else { 
      NotificationCenter.default.addObserver(self,selector: #selector(ViewController.monitorBatteryStatus), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil) 
     } 
} 

func monitorBatteryStatus() { 
if self.MonitorBatteryStatus(state: UIDevice.current.batteryState) == true { 
      self.updateUIForChargingTest() 
     } 
      else { 
      print("Device Battery State Unknown") 
     } 
} 

    func MonitorBatteryStatus(state : UIDeviceBatteryState) -> Bool { 

     switch state { 
     case UIDeviceBatteryState.charging: 
      return true 
     case UIDeviceBatteryState.full: 
      return true 
     default: 
      return false 
     } 
    } 

NSNotificationUIDeviceBatteryStateDidChangeNotificationトリガされないたびを使用してみました。毎回selectorメソッドを呼び出さない。 10回のうちにケーブルを差し込むと、2回だけ正常に応答します。デバイスが充電を開始しても。

一部の人が重複としてマークしています。だからあなたの親切な情報のために、これは正確な重複した質問ではありません。なぜなら、ここでは私のために働いていない問題に一定のアプローチを適用しているからです.AT ALL !!私の質問に似た質問で提供されるソリューションは、私のために働いています。私はすでにそれらを試してきました。

+0

に耳を傾けなければなりません。 –

+0

@LeoDabus ViewDidLoad自体に通知を追加しました。私はcheckForChargingメソッドを呼び出しました。デバイスがすでにビューロードで課金されている場合は、現在の状態をチェックします。そうでない場合には、それだけが通知をトリガーする。しかし、私の場合、この通知はランダムにトリガーされます。時にはそれが誘発し、時にはdoes not – Akaanksha

+0

あなたの質問を編集してコードを更新してください –

答えて

0

あなたはちょうどそれを有効にした後、あなたのviewDidLoadメソッド内のオブザーバを追加対象装置

 NotificationCenter.default.addObserver(self,selector: #selector(ViewController.monitorBatteryStatus), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: UIDevice.current) 
+0

さらに、メインスレッドで通知を聞くべきです。 – santhosh

関連する問題