I am building an iOS mobile application using Flutter, with native Swift integration for accessing Apple HealthKit instead of a Flutter plugin. The primary goal is to capture and sync specific HealthKit data types, namely Respiratory Rate and Sleeping Wrist Temperature, and send this data to a backend API as close to real-time as possible after it is written to HealthKit.
The application needs to support both foreground and background syncing. Data should be synced when the app is opened, but also in the background when the device is locked. Additionally, there are reliability constraints to consider: the user may not open the app for extended periods, the device may remain locked, and Low Power Mode or other system restrictions may impact background execution.
I have explored a few possible approaches. One option is using BGTaskScheduler to periodically fetch and sync data. However, based on my understanding, background tasks are not guaranteed to execute frequently and may be throttled or stopped by the system after some time.
Another approach is to use HKObserverQuery along with HKAnchoredObjectQuery. In this setup, observer queries would be registered for the required data types, background delivery would be enabled, and whenever triggered, anchored queries would fetch incremental updates which would then be sent to the backend. This seems closer to a real-time model, but I am unsure how reliable and timely these background updates are in practice.
I have also looked into newer APIs like HKQueryDescriptor, but it is not clear whether they provide any advantage over the observer plus anchored query approach for this use case.
My main questions are: what is the recommended architecture for achieving near real-time syncing of HealthKit data for these metrics? Does HealthKit background delivery provide any guarantees or expectations around delivery timing, or can updates be significantly delayed depending on system conditions? How should edge cases be handled, such as when the device remains locked for long durations or when Low Power Mode is enabled? Would it be advisable to combine observer queries with BGTaskScheduler as a fallback mechanism?
Finally, apps like Athlytic appear to show updated data immediately when opened. I am curious whether this is primarily achieved through background delivery or by fetching data on demand when the app becomes active.
The goal is to design a system that is as close to real-time as possible while remaining reliable and compliant with iOS background execution constraints. Any recommended patterns, best practices, or references would be greatly appreciated.