Skip to content

Instantly share code, notes, and snippets.

@Gevrai
Created April 13, 2018 19:23
Show Gist options
  • Save Gevrai/7093ba9074350e32c191392537388e49 to your computer and use it in GitHub Desktop.
Save Gevrai/7093ba9074350e32c191392537388e49 to your computer and use it in GitHub Desktop.
Very simple Singleton that sends a Notification whenever the state or level of the battery changed.
public class BatteryMonitoring {
public static let BatteryDidChangeNotification = Notification.Name(rawValue: "BatteryStateNotifier.BatteryDidChangeNotification")
public static let shared = BatteryMonitoring()
private init() {}
public private(set) var state : WKInterfaceDeviceBatteryState = .unknown
// State will be an int between 0 and 100 if state is not .unknown, else -1
public private(set) var level : Int = -1
private var timer : Timer?
public var isStarted : Bool { get { return timer != nil && timer!.isValid } }
public func start(withPeriod period : TimeInterval) {
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: period, target: self, selector: #selector(self.verifyAndNotifyOfChange), userInfo: nil, repeats: true)
timer?.fire()
}
public func stop() {
timer?.invalidate()
timer = nil
}
@objc private func verifyAndNotifyOfChange() {
let (newState, newLevel) = getBaterryInfo()
if newState != state || newLevel != level {
state = newState
level = newLevel
NotificationCenter.default.post( Notification(
name: BatteryMonitoring.BatteryDidChangeNotification,
object: (state, level),
userInfo: nil))
}
}
// Get the battery state without changing the isBatteryMonitoringEnabled value
// This is of course not atomic!
public func getBaterryInfo(forDevice device : WKInterfaceDevice = WKInterfaceDevice.current()) -> (WKInterfaceDeviceBatteryState, Int) {
let originalMonitoringValue = device.isBatteryMonitoringEnabled
defer {
device.isBatteryMonitoringEnabled = originalMonitoringValue
}
device.isBatteryMonitoringEnabled = true
return (device.batteryState, Int(100.0 * device.batteryLevel))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment