DisplayGlucosePreference.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // DisplayGlucosePreference.swift
  3. // LoopKitUI
  4. //
  5. // Created by Nathaniel Hamming on 2021-03-10.
  6. // Copyright © 2021 LoopKit Authors. All rights reserved.
  7. //
  8. import Foundation
  9. import HealthKit
  10. import SwiftUI
  11. import LoopKit
  12. public class DisplayGlucosePreference: ObservableObject {
  13. @Published public private(set) var unit: HKUnit
  14. @Published public private(set) var rateUnit: HKUnit
  15. @Published public private(set) var formatter: QuantityFormatter
  16. @Published public private(set) var minuteRateFormatter: QuantityFormatter
  17. public init(displayGlucoseUnit: HKUnit) {
  18. let rateUnit = displayGlucoseUnit.unitDivided(by: .minute())
  19. self.unit = displayGlucoseUnit
  20. self.rateUnit = rateUnit
  21. self.formatter = QuantityFormatter(for: displayGlucoseUnit)
  22. self.minuteRateFormatter = QuantityFormatter(for: rateUnit)
  23. self.formatter.numberFormatter.notANumberSymbol = "–"
  24. self.minuteRateFormatter.numberFormatter.notANumberSymbol = "–"
  25. }
  26. /// Formats a glucose HKQuantity and unit as a localized string
  27. ///
  28. /// - Parameters:
  29. /// - quantity: The quantity
  30. /// - includeUnit: Whether or not to include the unit in the returned string
  31. /// - Returns: A localized string, or the numberFormatter's notANumberSymbol (default is "–")
  32. open func format(_ quantity: HKQuantity, includeUnit: Bool = true) -> String {
  33. return formatter.string(from: quantity, includeUnit: includeUnit) ?? self.formatter.numberFormatter.notANumberSymbol
  34. }
  35. /// Formats a glucose HKQuantity rate (in terms of mg/dL/min or mmol/L/min and unit as a localized string
  36. ///
  37. /// - Parameters:
  38. /// - quantity: The quantity
  39. /// - includeUnit: Whether or not to include the unit in the returned string
  40. /// - Returns: A localized string, or the numberFormatter's notANumberSymbol (default is "–")
  41. open func formatMinuteRate(_ quantity: HKQuantity, includeUnit: Bool = true) -> String {
  42. return minuteRateFormatter.string(from: quantity, includeUnit: includeUnit) ?? self.formatter.numberFormatter.notANumberSymbol
  43. }
  44. }
  45. extension DisplayGlucosePreference: DisplayGlucoseUnitObserver {
  46. public func unitDidChange(to displayGlucoseUnit: HKUnit) {
  47. self.unit = displayGlucoseUnit
  48. self.formatter = QuantityFormatter(for: displayGlucoseUnit)
  49. }
  50. }