Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. import Foundation
  2. import WatchKit
  3.  
  4. public struct BatteryInfo {
  5.   var state: WKInterfaceDeviceBatteryState
  6.   var level: Float
  7. }
  8.  
  9. func batteryInfo(forDevice device: WKInterfaceDevice = .current())
  10.   -> BatteryInfo {
  11.   let originalMonitoringValue = device.isBatteryMonitoringEnabled
  12.  
  13.   defer {
  14.     device.isBatteryMonitoringEnabled = originalMonitoringValue
  15.   }
  16.  
  17.   device.isBatteryMonitoringEnabled = true
  18.  
  19.   return BatteryInfo(
  20.     state: device.batteryState,
  21.     level: device.batteryLevel * 100.0
  22.   )
  23. }
  24.  
  25. public class BatteryInfoNotifier {
  26.   public static let BatteryDidChangeNotification = Notification.Name(
  27.     rawValue: "BatteryInfoNotifier.BatteryInfoDidChangeNotification"
  28.   )
  29.  
  30.   public static let shared = BatteryInfoNotifier()
  31.   private init() {}
  32.  
  33.   public private(set) var info = BatteryInfo(state: .unknown, level: -1)
  34.   private var timer: Timer?
  35.  
  36.   public static let device = WKInterfaceDevice.current()
  37.  
  38.   public var isStarted: Bool {
  39.     return timer != nil && timer!.isValid
  40.   }
  41.  
  42.   public func start(withTimeInterval interval: TimeInterval = 60) {
  43.     timer?.invalidate()
  44.  
  45.     timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) {
  46.       [weak self] _ in
  47.  
  48.       let currentInfo = batteryInfo(forDevice: BatteryInfoNotifier.device)
  49.  
  50.       guard currentInfo.state != self?.info.state
  51.         || currentInfo.level != self?.info.level else {
  52.         return
  53.       }
  54.  
  55.       self?.info = currentInfo
  56.  
  57.       NotificationCenter.default.post(Notification(
  58.         name: BatteryInfoNotifier.BatteryDidChangeNotification,
  59.         object: self?.info,
  60.         userInfo: nil
  61.       ))
  62.     }
  63.  
  64.     timer!.fire()
  65.   }
  66.  
  67.   public func stop() {
  68.     timer?.invalidate()
  69.     timer = nil
  70.   }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement