Reportage/Services/Health/HealthReader.swift (4073B)
1import Foundation
2import HealthKit
3
4
5protocol HealthReading: Sendable {
6
7 func activity(from start: Date, to end: Date) async throws -> ActivityHealth
8
9 func sleepSamples(from start: Date, to end: Date) async throws -> [SleepSample]
10}
11
12
13struct SleepSample: Equatable, Sendable {
14 enum Stage: Equatable, Sendable {
15 case inBed
16
17 case asleep
18 case core
19 case deep
20 case rem
21 case awake
22 }
23
24
25 var source: String
26 var stage: Stage
27 var start: Date
28 var end: Date
29}
30
31struct HealthKitReader: HealthReading {
32 static let readTypes: Set<HKObjectType> = [
33 HKQuantityType(.stepCount),
34 HKQuantityType(.distanceWalkingRunning),
35 HKQuantityType(.flightsClimbed),
36 HKCategoryType(.sleepAnalysis),
37 ]
38
39 let store: HKHealthStore
40
41 func activity(from start: Date, to end: Date) async throws -> ActivityHealth {
42 async let steps = sum(.stepCount, unit: .count(), from: start, to: end)
43 async let distance = sum(.distanceWalkingRunning, unit: .meter(), from: start, to: end)
44 async let flights = sum(.flightsClimbed, unit: .count(), from: start, to: end)
45 return try await ActivityHealth(
46 steps: steps.map { Int($0.rounded()) },
47 distance: distance,
48 flightsClimbed: flights.map { Int($0.rounded()) })
49 }
50
51 func sleepSamples(from start: Date, to end: Date) async throws -> [SleepSample] {
52 let descriptor = HKSampleQueryDescriptor(
53 predicates: [
54 .categorySample(
55 type: HKCategoryType(.sleepAnalysis),
56 predicate: HKQuery.predicateForSamples(withStart: start, end: end))
57 ],
58 sortDescriptors: [SortDescriptor(\.startDate)])
59 return try await Self.ignoringNoData(default: []) {
60 try await descriptor.result(for: store).compactMap { sample in
61 guard let stage = Self.stage(sample.value) else { return nil }
62 return SleepSample(
63 source: sample.sourceRevision.source.bundleIdentifier,
64 stage: stage, start: sample.startDate, end: sample.endDate)
65 }
66 }
67 }
68
69
70
71 private func sum(
72 _ identifier: HKQuantityTypeIdentifier, unit: HKUnit, from start: Date, to end: Date
73 ) async throws -> Double? {
74 let descriptor = HKStatisticsQueryDescriptor(
75 predicate: .quantitySample(
76 type: HKQuantityType(identifier),
77 predicate: HKQuery.predicateForSamples(withStart: start, end: end)),
78 options: .cumulativeSum)
79 return try await Self.ignoringNoData(default: nil) {
80 try await descriptor.result(for: store)?.sumQuantity()?.doubleValue(for: unit)
81 }
82 }
83
84
85
86
87 private static func ignoringNoData<T>(default value: T, _ body: () async throws -> T) async throws -> T {
88 do {
89 return try await body()
90 } catch let error as HKError where error.code == .errorNoData {
91 return value
92 }
93 }
94
95 private static func stage(_ value: Int) -> SleepSample.Stage? {
96 switch HKCategoryValueSleepAnalysis(rawValue: value) {
97 case .inBed: .inBed
98 case .asleepUnspecified: .asleep
99 case .asleepCore: .core
100 case .asleepDeep: .deep
101 case .asleepREM: .rem
102 case .awake: .awake
103 default: nil
104 }
105 }
106}