@@ -6,14 +6,15 @@ import HealthKit
66/// tracks toothbrushing, in number of sessions per day (daystamp)
77class ToothbrushingDailySessionsHealthKitMetric : CategoryHealthKitMetric {
88 private static let healthkitMetric = [ " toothbrushing " , " sessions-per-day " ] . joined ( separator: " | " )
9+ private static let hkSampleType = HKObjectType . categoryType ( forIdentifier: . toothbrushingEvent) !
910
1011 init ( humanText: String = " Teethbrushing (in sessions per day) " ,
1112 databaseString: String = ToothbrushingDailySessionsHealthKitMetric . healthkitMetric,
1213 category: HealthKitCategory = . Other) {
1314 super. init ( humanText: humanText,
1415 databaseString: databaseString,
1516 category: category,
16- hkSampleType: HKObjectType . categoryType ( forIdentifier : . toothbrushingEvent ) ! )
17+ hkSampleType: Self . hkSampleType )
1718 }
1819
1920 override func units( healthStore : HKHealthStore ) async throws -> HKUnit {
@@ -27,7 +28,17 @@ class ToothbrushingDailySessionsHealthKitMetric: CategoryHealthKitMetric {
2728 let predicate = HKQuery . predicateForSamples ( withStart: startDaystamp. start ( deadline: deadline) ,
2829 end: todayDaystamp. end ( deadline: deadline) )
2930
30- let samples = try await withCheckedThrowingContinuation ( { ( continuation: CheckedContinuation < [ HKSample ] , Error > ) in
31+ let samples = try await queryHealthStore ( healthStore, predicate: predicate)
32+
33+ let dailyCounts = calculateDailyCounts ( samples: samples)
34+
35+ let datapoints = makeDatapoints ( dailyCounts: dailyCounts, deadline: deadline)
36+
37+ return datapoints
38+ }
39+
40+ func queryHealthStore( _ healthStore: HKHealthStore , predicate: NSPredicate ) async throws -> [ HKCategorySample ] {
41+ try await withCheckedThrowingContinuation ( { ( continuation: CheckedContinuation < [ HKSample ] , Error > ) in
3142 let query = HKSampleQuery ( sampleType: sampleType ( ) ,
3243 predicate: predicate,
3344 limit: HKObjectQueryNoLimit,
@@ -44,7 +55,9 @@ class ToothbrushingDailySessionsHealthKitMetric: CategoryHealthKitMetric {
4455 healthStore. execute ( query)
4556 } )
4657 . compactMap { $0 as? HKCategorySample }
47-
58+ }
59+
60+ func calculateDailyCounts( samples: [ HKCategorySample ] ) -> [ ( Date , Int ) ] {
4861 let calendar = Calendar . autoupdatingCurrent
4962 let groupedByDay = Dictionary ( grouping: samples, by: { sample in
5063 calendar. startOfDay ( for: sample. startDate)
@@ -54,6 +67,10 @@ class ToothbrushingDailySessionsHealthKitMetric: CategoryHealthKitMetric {
5467 . map { ( $0, $1. count) }
5568 . sorted { $0. 0 < $1. 0 }
5669
70+ return dailyCounts
71+ }
72+
73+ func makeDatapoints( dailyCounts: [ ( Date , Int ) ] , deadline: Int ) -> [ any BeeDataPoint ] {
5774 let datapoints = dailyCounts. map ( { ( date, numberOfEntries) in
5875 let daystamp = Daystamp ( fromDate: date, deadline: deadline)
5976 let requestID = " apple-heath- " + daystamp. description
0 commit comments