HealthKitService.swift
8.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import Foundation
import HealthKit
/// Native Apple Health service for the Flutter host API.
///
/// Responsibilities:
/// - request/read HealthKit permissions
/// - read the health data types used by the original SwiftUI app
/// - keep Watch complication values fresh in the shared App Group
/// - register background observers so HealthKit changes refresh local state
final class HealthKitService {
static let shared = HealthKitService()
private let healthStore = HKHealthStore()
private let syncStore = HealthSyncStateStore()
private lazy var reader = HealthDataReader(healthStore: healthStore)
private var observersStarted = false
private init() {}
var isHealthDataAvailable: Bool {
HKHealthStore.isHealthDataAvailable()
}
func requestAuthorization(completion: @escaping (Bool, Error?) -> Void) {
guard isHealthDataAvailable else {
completion(false, NativeHealthKitError.healthDataUnavailable)
return
}
healthStore.requestAuthorization(
toShare: NativeHealthTypeCatalog.writeTypes,
read: NativeHealthTypeCatalog.readTypes
) { success, error in
completion(success, error)
}
}
func shouldRequestAuthorization() async -> Bool {
guard isHealthDataAvailable else { return false }
do {
let status = try await healthStore.statusForAuthorizationRequest(
toShare: NativeHealthTypeCatalog.writeTypes,
read: NativeHealthTypeCatalog.readTypes
)
return status == .shouldRequest
} catch {
return true
}
}
func startBackgroundObserversIfNeeded() {
guard isHealthDataAvailable, !observersStarted else { return }
observersStarted = true
for sampleType in NativeHealthTypeCatalog.observedTypes {
enableBackgroundDelivery(for: sampleType)
let query = HKObserverQuery(sampleType: sampleType, predicate: nil) { [weak self] _, completion, error in
guard error == nil else {
completion()
return
}
Task {
await self?.handleObservedChange(sampleType)
completion()
}
}
healthStore.execute(query)
}
}
func performLocalSync() async -> NativeHealthSyncSummary {
guard isHealthDataAvailable else {
return NativeHealthSyncSummary(commonCount: 0, sleepCount: 0, startedAt: Date(), endedAt: Date())
}
let startDate = earliestStartDate()
let endDate = Date()
do {
let summary = try await reader.collectRecentData(startDate: startDate, endDate: endDate)
NativeHealthDataType.allCases
.filter { $0 != .unknown }
.forEach { syncStore.save(date: endDate, for: $0) }
await refreshSharedWatchValues()
startBackgroundObserversIfNeeded()
return summary
} catch {
await refreshSharedWatchValues()
return NativeHealthSyncSummary(commonCount: 0, sleepCount: 0, startedAt: startDate, endedAt: endDate)
}
}
func refreshSharedWatchValues() async {
do {
if let hrv = try await reader.fetchLatestHRV() {
AppGroupConstants.defaults?.set(hrv, forKey: AppGroupConstants.Key.latestHRV)
}
} catch {
// Keep the previous widget value when a single read fails.
}
do {
let steps = try await reader.fetchTodayStepCount()
AppGroupConstants.defaults?.set(steps, forKey: AppGroupConstants.Key.latestStepCount)
} catch {
// Keep the previous widget value when a single read fails.
}
}
func fetchHrvData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchHrvData(startDate: startDate, endDate: endDate)
}
func fetchHeartRateData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchHeartRateData(startDate: startDate, endDate: endDate)
}
func fetchWalkingHeartRateData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchWalkingHeartRateData(startDate: startDate, endDate: endDate)
}
func fetchRestingHeartRateData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchRestingHeartRateData(startDate: startDate, endDate: endDate)
}
func fetchSleepingHeartRateData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchSleepingHeartRateData(startDate: startDate, endDate: endDate)
}
func fetchOxygenSaturationData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchOxygenSaturationData(startDate: startDate, endDate: endDate)
}
func fetchActiveEnergyData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchActiveEnergyData(startDate: startDate, endDate: endDate)
}
func fetchExerciseData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchExerciseData(startDate: startDate, endDate: endDate)
}
func fetchStandData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchStandData(startDate: startDate, endDate: endDate)
}
func fetchStepCountData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchStepCountData(startDate: startDate, endDate: endDate)
}
func fetchSleepData(startDate: Date, endDate: Date) async throws -> [NativeSleepInterval] {
try await reader.fetchSleepData(startDate: startDate, endDate: endDate)
}
func fetchSleepingWristTemperatureData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchSleepingWristTemperatureData(startDate: startDate, endDate: endDate)
}
func fetchRespiratoryRateData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchRespiratoryRateData(startDate: startDate, endDate: endDate)
}
func fetchIrregularHeartRhythmData(startDate: Date, endDate: Date) async throws -> [NativeHealthDataPoint] {
try await reader.fetchIrregularHeartRhythmData(startDate: startDate, endDate: endDate)
}
func fetchActivityTargetData(startDate: Date, endDate: Date) async throws -> NativeActivityTarget? {
try await reader.fetchActivityTargetData(startDate: startDate, endDate: endDate)
}
private func earliestStartDate() -> Date {
NativeHealthDataType.allCases
.filter { $0 != .unknown }
.map { syncStore.startDate(for: $0) }
.min() ?? Calendar.current.startOfDay(for: Date())
}
private func enableBackgroundDelivery(for sampleType: HKSampleType) {
let frequency: HKUpdateFrequency = sampleType.identifier == HKQuantityTypeIdentifier.stepCount.rawValue
? .hourly
: .immediate
healthStore.enableBackgroundDelivery(for: sampleType, frequency: frequency) { success, error in
if let error {
print("HealthKit background delivery failed: \(sampleType.identifier), \(error.localizedDescription)")
} else {
print("HealthKit background delivery \(success ? "enabled" : "not enabled"): \(sampleType.identifier)")
}
}
}
private func handleObservedChange(_ sampleType: HKSampleType) async {
switch sampleType.identifier {
case HKQuantityTypeIdentifier.heartRateVariabilitySDNN.rawValue,
HKQuantityTypeIdentifier.stepCount.rawValue:
await refreshSharedWatchValues()
default:
break
}
if let type = NativeHealthDataType(sampleTypeIdentifier: sampleType.identifier) {
syncStore.save(date: Date(), for: type)
}
}
}
private extension NativeHealthDataType {
init?(sampleTypeIdentifier: String) {
switch sampleTypeIdentifier {
case HKQuantityTypeIdentifier.heartRateVariabilitySDNN.rawValue:
self = .hrv
case HKQuantityTypeIdentifier.heartRate.rawValue:
self = .heartRate
case HKQuantityTypeIdentifier.stepCount.rawValue:
self = .steps
case HKQuantityTypeIdentifier.oxygenSaturation.rawValue:
self = .oxygenSaturation
case HKQuantityTypeIdentifier.activeEnergyBurned.rawValue:
self = .activeEnergy
case HKQuantityTypeIdentifier.appleExerciseTime.rawValue:
self = .exercise
case HKQuantityTypeIdentifier.appleStandTime.rawValue:
self = .stand
case HKQuantityTypeIdentifier.appleSleepingWristTemperature.rawValue:
self = .sleepingWristTemperature
case HKQuantityTypeIdentifier.respiratoryRate.rawValue:
self = .respiratoryRate
case HKCategoryTypeIdentifier.sleepAnalysis.rawValue:
self = .sleep
case HKCategoryTypeIdentifier.irregularHeartRhythmEvent.rawValue:
self = .irregularHeartRhythm
default:
return nil
}
}
}