HealthKitService.swift
5.71 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
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.
}
}
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
}
}
}