From c85a66544beb469f67edd032c490fae684e495cb Mon Sep 17 00:00:00 2001 From: Pete Schwamb Date: Thu, 10 May 2018 08:00:43 -0500 Subject: [PATCH] Fix missing glucose value display --- Common/Models/WatchContext.swift | 21 ++++++++++----------- WatchApp Extension/ExtensionDelegate.swift | 18 ++++++++++++++++-- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/Common/Models/WatchContext.swift b/Common/Models/WatchContext.swift index 1a3bb4da5e..f28140d222 100644 --- a/Common/Models/WatchContext.swift +++ b/Common/Models/WatchContext.swift @@ -56,14 +56,14 @@ final class WatchContext: NSObject, RawRepresentable { if let unitString = rawValue["gu"] as? String { let unit = HKUnit(from: unitString) preferredGlucoseUnit = unit + } - if let glucoseValue = rawValue["gv"] as? Double { - glucose = HKQuantity(unit: unit, doubleValue: glucoseValue) - } + if let glucoseValue = rawValue["gv"] as? Double { + glucose = HKQuantity(unit: preferredGlucoseUnit ?? .milligramsPerDeciliter(), doubleValue: glucoseValue) + } - if let glucoseValue = rawValue["egv"] as? Double { - eventualGlucose = HKQuantity(unit: unit, doubleValue: glucoseValue) - } + if let glucoseValue = rawValue["egv"] as? Double { + eventualGlucose = HKQuantity(unit: preferredGlucoseUnit ?? .milligramsPerDeciliter(), doubleValue: glucoseValue) } glucoseTrendRawValue = rawValue["gt"] as? Int @@ -102,11 +102,10 @@ final class WatchContext: NSObject, RawRepresentable { raw["bp"] = batteryPercentage raw["cob"] = COB - if let unit = preferredGlucoseUnit { - raw["egv"] = eventualGlucose?.doubleValue(for: unit) - raw["gu"] = unit.unitString - raw["gv"] = glucose?.doubleValue(for: unit) - } + let unit = preferredGlucoseUnit ?? .milligramsPerDeciliter() + raw["egv"] = eventualGlucose?.doubleValue(for: unit) + raw["gu"] = preferredGlucoseUnit?.unitString + raw["gv"] = glucose?.doubleValue(for: unit) raw["gt"] = glucoseTrendRawValue raw["gd"] = glucoseDate diff --git a/WatchApp Extension/ExtensionDelegate.swift b/WatchApp Extension/ExtensionDelegate.swift index 2e76860093..6d3ccada38 100644 --- a/WatchApp Extension/ExtensionDelegate.swift +++ b/WatchApp Extension/ExtensionDelegate.swift @@ -8,6 +8,7 @@ import WatchConnectivity import WatchKit +import HealthKit import os import UserNotifications @@ -152,10 +153,23 @@ final class ExtensionDelegate: NSObject, WKExtensionDelegate { } } + private lazy var healthStore = HKHealthStore() + fileprivate func updateContext(_ data: [String: Any]) { if let context = WatchContext(rawValue: data as WatchContext.RawValue) { - DispatchQueue.main.async { - self.lastContext = context + if context.preferredGlucoseUnit == nil { + let type = HKQuantityType.quantityType(forIdentifier: .bloodGlucose)! + healthStore.preferredUnits(for: [type]) { (units, error) in + context.preferredGlucoseUnit = units[type] + + DispatchQueue.main.async { + self.lastContext = context + } + } + } else { + DispatchQueue.main.async { + self.lastContext = context + } } } }