2017-07-31 12 views
-2

Appleの時計アプリのラベルにiPhoneの電池残量を表示しようとしています。 WatchConnectivityを使ってみて、iPhoneとApple Watchの間でメッセージを送信しようとしましたが、うまくいきませんでした。私はそれを行うことができる方法はありますか?Appleの時計にiPhoneのバッテリーを表示

+0

試したことや遭遇したエラーを教えてください。ウォッチからiPhoneと通信するには、実際に 'WatchConnectivity'フレームワークを使用する必要があります。 –

答えて

2

まずちょうどバッテリ監視を有効にします。

UIDevice.current.isBatteryMonitoringEnabled = true 

次にあなたがバッテリーレベルを返すように計算されたプロパティを作成することができます

var batteryLevel: Float { 
    return UIDevice.current.batteryLevel 
} 

あなたがのためにオブザーバーを追加することができ、あなたのデバイスのバッテリーレベルを監視するにはUIDeviceBatteryLevelDidChange通知:

NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: .UIDeviceBatteryLevelDidChange, object: nil) 
func batteryLevelDidChange(_ notification: Notification) { 
    print(batteryLevel) 
} 

また、バッテリーの状態を確認してください。

var batteryState: UIDeviceBatteryState { 
    return UIDevice.current.batteryState 
} 
case .unknown // "The battery state for the device cannot be determined." 
case .unplugged // "The device is not plugged into power; the battery is discharging" 
case .charging // "The device is plugged into power and the battery is less than 100% charged." 
case .full  // "The device is plugged into power and the battery is 100% charged." 

をしてUIDeviceBatteryStateDidChange通知のオブザーバを追加します。

NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: .UIDeviceBatteryStateDidChange, object: nil) 
func batteryStateDidChange(_ notification: Notification) { 
    switch batteryState { 
    case .unplugged, .unknown: 
     print("not charging") 
    case .charging, .full: 
     print("charging or full") 
    } 
} 

は今、あなたは、あなたのバッテリーに関する必要なすべてのプロパティを持っています。ちょうど時計にそれらを渡す!

これが役に立ちます。

関連する問題