|
| 1 | +import Foundation |
| 2 | +import HealthKit |
| 3 | + |
| 4 | +/// Manages HealthKit background delivery by registering observer queries at app launch, |
| 5 | +/// before the JS bridge is available. This is required by Apple — observer queries must |
| 6 | +/// be set up in `application(_:didFinishLaunchingWithOptions:)` to receive background |
| 7 | +/// delivery callbacks after the app has been terminated. |
| 8 | +/// |
| 9 | +/// Usage from AppDelegate.swift: |
| 10 | +/// BackgroundDeliveryManager.shared.setupBackgroundObservers() |
| 11 | +/// |
| 12 | +/// The types to observe are persisted in UserDefaults by `configureBackgroundTypes()` |
| 13 | +/// called from JS. On subsequent cold launches, the manager reads these and registers |
| 14 | +/// observers immediately, queuing any events until JS subscribes via `drainPendingEvents()`. |
| 15 | +@objc public class BackgroundDeliveryManager: NSObject { |
| 16 | + @objc public static let shared = BackgroundDeliveryManager() |
| 17 | + |
| 18 | + private let healthStore = HKHealthStore() |
| 19 | + private let queue = DispatchQueue(label: "com.kingstinct.healthkit.background", attributes: .concurrent) |
| 20 | + private var observerQueries: [String: HKObserverQuery] = [:] |
| 21 | + private var pendingEvents: [(typeIdentifier: String, errorMessage: String?)] = [] |
| 22 | + private var jsCallback: ((String, String?) -> Void)? |
| 23 | + private var isSetUp = false |
| 24 | + |
| 25 | + static let typesKey = "com.kingstinct.healthkit.backgroundTypes" |
| 26 | + static let frequencyKey = "com.kingstinct.healthkit.backgroundFrequency" |
| 27 | + |
| 28 | + private override init() { |
| 29 | + super.init() |
| 30 | + } |
| 31 | + |
| 32 | + /// Call this from AppDelegate.didFinishLaunchingWithOptions to register observer queries |
| 33 | + /// for any previously configured background delivery types. |
| 34 | + @objc public func setupBackgroundObservers() { |
| 35 | + guard HKHealthStore.isHealthDataAvailable() else { return } |
| 36 | + |
| 37 | + guard let typeIdentifiers = UserDefaults.standard.stringArray(forKey: BackgroundDeliveryManager.typesKey) else { |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + let frequencyRaw = UserDefaults.standard.integer(forKey: BackgroundDeliveryManager.frequencyKey) |
| 42 | + let frequency = HKUpdateFrequency(rawValue: frequencyRaw) ?? .immediate |
| 43 | + |
| 44 | + registerObservers(typeIdentifiers: typeIdentifiers, frequency: frequency) |
| 45 | + } |
| 46 | + |
| 47 | + /// Persist types and frequency, then register observers for the current session. |
| 48 | + /// Called from JS via CoreModule.configureBackgroundTypes(). |
| 49 | + func configure(typeIdentifiers: [String], frequency: HKUpdateFrequency) { |
| 50 | + UserDefaults.standard.set(typeIdentifiers, forKey: BackgroundDeliveryManager.typesKey) |
| 51 | + UserDefaults.standard.set(frequency.rawValue, forKey: BackgroundDeliveryManager.frequencyKey) |
| 52 | + |
| 53 | + // Tear down existing observers before re-registering |
| 54 | + tearDown() |
| 55 | + registerObservers(typeIdentifiers: typeIdentifiers, frequency: frequency) |
| 56 | + } |
| 57 | + |
| 58 | + /// Subscribe a JS callback. Any events that arrived before JS was ready are flushed immediately. |
| 59 | + func setCallback(_ callback: @escaping (String, String?) -> Void) { |
| 60 | + queue.sync(flags: .barrier) { |
| 61 | + self.jsCallback = callback |
| 62 | + let events = self.pendingEvents |
| 63 | + self.pendingEvents = [] |
| 64 | + |
| 65 | + for event in events { |
| 66 | + callback(event.typeIdentifier, event.errorMessage) |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + /// Remove the JS callback (e.g., on teardown). |
| 72 | + func removeCallback() { |
| 73 | + queue.sync(flags: .barrier) { |
| 74 | + self.jsCallback = nil |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + /// Returns any pending events and clears the queue. Used by CoreModule.subscribeToObserverQuery |
| 79 | + /// to flush events that arrived before JS subscribed. |
| 80 | + func drainPendingEvents() -> [(typeIdentifier: String, errorMessage: String?)] { |
| 81 | + return queue.sync(flags: .barrier) { |
| 82 | + let events = self.pendingEvents |
| 83 | + self.pendingEvents = [] |
| 84 | + return events |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + /// Stop all observer queries and clear state. |
| 89 | + func tearDown() { |
| 90 | + queue.sync(flags: .barrier) { |
| 91 | + for (_, query) in self.observerQueries { |
| 92 | + self.healthStore.stop(query) |
| 93 | + } |
| 94 | + self.observerQueries = [:] |
| 95 | + self.isSetUp = false |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + /// Clear persisted configuration (disables background delivery on next launch). |
| 100 | + func clearConfiguration() { |
| 101 | + UserDefaults.standard.removeObject(forKey: BackgroundDeliveryManager.typesKey) |
| 102 | + UserDefaults.standard.removeObject(forKey: BackgroundDeliveryManager.frequencyKey) |
| 103 | + tearDown() |
| 104 | + } |
| 105 | + |
| 106 | + private func registerObservers(typeIdentifiers: [String], frequency: HKUpdateFrequency) { |
| 107 | + queue.sync(flags: .barrier) { |
| 108 | + guard !self.isSetUp else { return } |
| 109 | + self.isSetUp = true |
| 110 | + } |
| 111 | + |
| 112 | + for typeIdentifier in typeIdentifiers { |
| 113 | + guard let sampleType = sampleTypeFromString(typeIdentifier) else { |
| 114 | + print("[react-native-healthkit] BackgroundDeliveryManager: skipping unrecognized type \(typeIdentifier)") |
| 115 | + continue |
| 116 | + } |
| 117 | + |
| 118 | + // Use nil predicate to catch all samples, including those written while the app was terminated. |
| 119 | + // The current subscribeToObserverQuery uses Date.init() which misses data from when the app was dead. |
| 120 | + let query = HKObserverQuery( |
| 121 | + sampleType: sampleType, |
| 122 | + predicate: nil |
| 123 | + ) { [weak self] (_: HKObserverQuery, completionHandler: @escaping HKObserverQueryCompletionHandler, error: Error?) in |
| 124 | + self?.handleObserverCallback( |
| 125 | + typeIdentifier: typeIdentifier, |
| 126 | + error: error |
| 127 | + ) |
| 128 | + // Must call the completion handler promptly so iOS knows we processed the update. |
| 129 | + completionHandler() |
| 130 | + } |
| 131 | + |
| 132 | + healthStore.execute(query) |
| 133 | + |
| 134 | + healthStore.enableBackgroundDelivery(for: sampleType, frequency: frequency) { success, error in |
| 135 | + if let error = error { |
| 136 | + print("[react-native-healthkit] BackgroundDeliveryManager: enableBackgroundDelivery failed for \(typeIdentifier): \(error.localizedDescription)") |
| 137 | + } else if !success { |
| 138 | + print("[react-native-healthkit] BackgroundDeliveryManager: enableBackgroundDelivery returned false for \(typeIdentifier)") |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + queue.sync(flags: .barrier) { |
| 143 | + self.observerQueries[typeIdentifier] = query |
| 144 | + } |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + private func handleObserverCallback(typeIdentifier: String, error: Error?) { |
| 149 | + let errorMessage = error?.localizedDescription |
| 150 | + |
| 151 | + queue.sync(flags: .barrier) { |
| 152 | + if let callback = self.jsCallback { |
| 153 | + // JS is connected — dispatch to main thread for JSI safety |
| 154 | + DispatchQueue.main.async { |
| 155 | + callback(typeIdentifier, errorMessage) |
| 156 | + } |
| 157 | + } else { |
| 158 | + // JS not ready yet — queue the event for later |
| 159 | + self.pendingEvents.append((typeIdentifier: typeIdentifier, errorMessage: errorMessage)) |
| 160 | + } |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + // Local type resolution that doesn't depend on NitroModules (which isn't available at AppDelegate time) |
| 165 | + private func sampleTypeFromString(_ identifier: String) -> HKSampleType? { |
| 166 | + if identifier.starts(with: "HKQuantityTypeIdentifier") { |
| 167 | + return HKQuantityType(HKQuantityTypeIdentifier(rawValue: identifier)) |
| 168 | + } |
| 169 | + if identifier.starts(with: "HKCategoryTypeIdentifier") { |
| 170 | + return HKCategoryType(HKCategoryTypeIdentifier(rawValue: identifier)) |
| 171 | + } |
| 172 | + if identifier == "HKWorkoutTypeIdentifier" { |
| 173 | + return HKSampleType.workoutType() |
| 174 | + } |
| 175 | + if identifier.starts(with: "HKCorrelationTypeIdentifier") { |
| 176 | + return HKCorrelationType(HKCorrelationTypeIdentifier(rawValue: identifier)) |
| 177 | + } |
| 178 | + if identifier == "HKAudiogramSampleType" { |
| 179 | + return HKObjectType.audiogramSampleType() |
| 180 | + } |
| 181 | + if identifier == "HKDataTypeIdentifierHeartbeatSeries" || identifier == "HKWorkoutRouteTypeIdentifier" { |
| 182 | + return HKObjectType.seriesType(forIdentifier: identifier) |
| 183 | + } |
| 184 | + if identifier == "HKElectrocardiogramType" { |
| 185 | + return HKSampleType.electrocardiogramType() |
| 186 | + } |
| 187 | + return nil |
| 188 | + } |
| 189 | +} |
0 commit comments