Use HealthKit to enable your iOS and watchOS apps to work with the Apple Health app.

All subtopics
Posts under Health and Fitness topic

Post

Replies

Boosts

Views

Activity

Unable to receive HealthKit updates when app is force-quit — need clarification on background delivery limits
Hello, I’m developing a HealthKit-based fitness app in React Native that observes step count changes and uploads the latest totals to a remote server. I’m currently using HKObserverQuery with background delivery enabled (enableBackgroundDelivery(for:frequency:.immediate)), and the behavior works correctly while the app is running in the background or foreground. Whenever new step data is written to HealthKit, the app wakes up, reads the latest data, and sends it to my HTTPS endpoint using URLSession.shared.dataTask inside the observer callback. However, I’ve noticed the following issue: 1. If the user swipes up (force-quits) the app from the app switcher, the observer queries stop firing entirely. 2. In this state, even though HealthKit continues collecting step data from the device or Apple Watch, my app no longer receives those background deliveries until the user opens the app again. What I would like to achieve is: When the app is terminated (swiped up), and there are new step count updates in HealthKit, my app should still be able to receive those updates or be relaunched to handle them — similar to how some health companion apps continue syncing data and sending notifications even after being force-quit. So I have a few questions: Is this limitation expected — i.e., does iOS intentionally block HKObserverQuery background deliveries after a user force-quits the app? 2. Are there any special entitlements, background modes, or Apple-approved mechanisms that allow a health or medical app to continue receiving HealthKit changes even after a force-quit? 3. If not, what is the recommended architecture for apps that need to process HealthKit data continuously and send it to a backend server? For example, should such apps rely on server-side push notifications or CloudKit sync once the user reopens the app? My current goal is to ensure step count changes are uploaded reliably even if the app is killed, but I want to stay within the system’s supported behaviors and privacy constraints. Any clarification or guidance from Apple engineers or others who have implemented continuous HealthKit sync (like companion or medical apps) would be greatly appreciated. Thank you.
1
0
16
3d
HKObserverQuery and BackgroundDelivery Are Highly Unstable on watchOS 26
We are developing a health app that relies on HKObserverQuery and BackgroundDelivery to monitor Heart Rate data. On watchOS 10.6 and 11.6 , these data updates are typically delivered reliably every 8–12 minutes, occasionally exceeding 12 minutes, but generally not longer than 15 minutes. This frequency has been sufficient for the real-time data requirements of our app. However, after adapting our app to watchOS 26, we noticed that HKObserverQuery triggers much less frequently, with longer and very inconsistent intervals. This issue has had a major impact on our product: data collection for essential features is unreliable, resulting in a greatly diminished user experience on watchOS 26 and making the app essentially useless from the user’s perspective. Observed Behavior: HKObserverQuery and BackgroundDelivery are extremely unstable, with trigger intervals frequently exceeding 15 minutes, and sometimes even 20 minutes. When the user is sedentary, intervals become even longer; there are cases where no heart rate or active energy updates are delivered for 30 minutes, or even over 1 hour. Request for Support and Guidance: Have there been any changes to the HKObserverQuery background delivery mechanism on watchOS 26, specifically for Heart Rate and Active Energy data? If these changes are intentional system optimizations, could you provide guidance or recommended practices to ensure our app can reliably retrieve updates and maintain a smooth experience for users? Thank you for your support.
2
0
130
4d
Feature Request: Expand HealthKit Body Composition Data Types to Support Smart Body Scanning Scales
Summary: Expanding HealthKit to support the full spectrum of smart scale metrics will allow Apple Health to remain the central hub for health data, align with user expectations, and future-proof the framework as body composition analysis evolves. Description: With the growing adoption of smart body composition scales (e.g. segmental impedance scanners, multi-frequency analyzers, and body pods), users are generating a wide variety of clinically relevant metrics that currently cannot be stored natively in HealthKit. At present, HealthKit supports a core set of body composition values (Body Mass, BMI, Body Fat %, Lean Mass, Height, Waist Circumference). While useful, these do not capture the full picture modern devices provide, leading to fragmentation: • Users can see dozens of metrics in the device app, but only a handful flow into Health. • Developers must resort to metadata fields, which are inconsistent across apps and not accessible in Apple’s Health app UI. This gap undermines HealthKit’s role as a central, standardized health record. ⸻ Proposed Additions: Expand HealthKit HKQuantityTypeIdentifier to include additional body composition and derived measurements commonly reported by smart scales: Core Body Composition • Visceral fat percentage / rating • Skeletal muscle mass • Segmental muscle mass (arms, legs, trunk) • Segmental fat mass (arms, legs, trunk) • Bone mineral mass • Total body water % / hydration Derived Health Metrics • Muscle-to-fat ratio • Phase angle (bioelectrical impedance) • Metabolic age • Basal metabolic rate (BMR) ⸻ Rationale: • User benefit: Health app would show a more complete health profile, not just weight and fat %. • Developer benefit: Creates standardized identifiers, eliminating the need for proprietary storage in metadata. • Industry alignment: Many leading health devices already provide these metrics; users expect them to sync into Health. • Future-proofing: As body scanning scales proliferate, HealthKit can remain the trusted central repository rather than ceding ground to siloed vendor apps. ⸻ Suggested Implementation: • Introduce new HKQuantityTypeIdentifier values for each metric. • Permit segmental values to be represented as discrete samples with metadata for body region. • Ensure values can be written by apps/devices and surfaced in Health app UI, just like existing body composition data.
1
0
65
1w
Possible to bring back "Time in Bed" iOS feature?
I have an iPhone 11 Pro Max running iOS 26. But since iOS 18, Apple decided to remove the "Time in Bed" feature[1][2]. Is it possible to develop an app that, effectively, "brings back" this feature? It doesn't have to be that accurate. Just a gauge is fine. As a starter I would like to track the time the phone was in Sleep mode (regardless whether the phone is being used). I have a minimal programming background but have not developed an iOS app before so any help would be appreciated. I found out about HealthKit[3] which lets me access (edit?) Health data, but I don't know where to go from there. [1] https://www.reddit.com/r/iOSBeta/comments/1em8bl6/ios_181_db1_time_in_bed_via_iphone_feature_removed [2] https://www.reddit.com/r/ios/comments/1fkjat4/apple_removed_the_iphoneonly_sleep_tracking [3] https://developer.apple.com/documentation/healthkit
1
0
565
1w
How to accurately query HKWorkout segment data
Hello, In my application, I need to obtain precise workout segment data from HKWorkout in order to calculate per-kilometer metrics such as heart rate and pace. My current approach is: 1.Use HKWorkout to fetch the associated HKWorkoutEvents. 2.Take the end time of one event as the start time of the next event to derive per-kilometer segment ranges. The issue I’m facing: •If a user sets Apple Watch to notify every 5 kilometers, then at 5 km, 10 km, 15 km, etc., I see overlapping event times. •From the HKWorkoutEvents data alone, I cannot distinguish between events that represent “per-kilometer splits” and those that represent “5-kilometer notifications.” •As a result, my per-kilometer heart rate and pace calculations can be inaccurate. My question is: Is there a recommended way to reliably differentiate per-kilometer splits from custom distance notifications and ensure accurate segment data retrieval? For example, should I instead reconstruct segments using HKWorkoutRoute and distance samples, rather than relying on HKWorkoutEvents? STEPS TO REPRODUCE 1.On Apple Watch, start an Outdoor Run using the Workout app. 2.In workout notifications, set distance alerts to every 5 kilometers. 3.During the run, when reaching 5 km, 10 km, 15 km, etc., the watch triggers notifications. 4.Query the corresponding HKWorkout from HealthKit and inspect its HKWorkoutEvents. 5.Notice that some event start times are duplicated, and it is unclear which events represent “per-kilometer splits” and which represent “5-kilometer notifications.” Expected Result: Be able to differentiate between per-kilometer splits and custom distance alerts, so that heart rate and pace per kilometer can be calculated accurately. Actual Result: The HKWorkoutEvents data contains duplicated event times without a way to distinguish event types, leading to inaccurate per-kilometer statistics.
3
0
96
1w
HKObserverQuery stops delivering updates in background on watchOS 26
Hello, I’m building a health-related app for both watchOS and iOS, which needs to monitor certain health data (e.g., heart rate, active energy). Before updating to watchOS 26, the queries worked reliably without any issues. However, after adapting to watchOS 26, some users have reported that health data updates stop being delivered. What I’ve observed: HKObserverQuery with enableBackgroundDelivery is set up normally. On WatchOS 26, the query sometimes stops delivering updates entirely after a certain point, and once an update is missed, it may stop delivering further updates completely. Restarting the Apple Watch temporarily restores delivery, but the problem reoccurs after some time. This makes background health data monitoring unreliable for my app. Here’s a simplified version of the code we are using: guard let heartType = HKObjectType.quantityType(forIdentifier: .heartRate) else { return } let query = HKObserverQuery(sampleType: heartType, predicate: nil) { query, completionHandler, error in if let error = error { logEvent("Observer error: \(error.localizedDescription)") return } logEvent("Heart rate changed") MyNotificationManager.shared.sendNotification() // Send a local notification completionHandler() } healthStore.execute(query) healthStore.enableBackgroundDelivery(for: heartType, frequency: .hourly) { success, error in if success { logEvent("Background heart rate delivery enabled") } else { logEvent("Failed to enable background heart rate delivery: \(error?.localizedDescription ?? "Unknown error")") } } Could you please clarify: Is this a known issue with HKObserverQuery and enableBackgroundDelivery on watchOS 26? Are there any recommended workarounds or best practices to ensure continuous background delivery of health data? Thank you in advance for your help.
4
1
215
1w
Rejected using Healthkit
Hi all, I'm developing fitness app and I use healthkit to track user's "STEPS" count from their iphone devices. I have been receiving this rejection and can't seem to get past this: Guideline 2.5.1 - Performance - Software Requirements The app uses the HealthKit or CareKit APIs but does not clearly identify the HealthKit and CareKit functionality in the app's user interface. Apps using these APIs should be clearly indicated to provide transparency and valuable information to users. Next Steps To resolve this issue, it would appropriate to clearly identify the HealthKit and CareKit functionality in the app's user interface. Resources Learn more about software requirements in guideline 2.5.1. I have modified my app: adding user permission prompt, adding healthkit notification, adding healthkit indicator in the UI, adding healthkit information in the onboarding process. I keep getting the same message. When I asked the reviewer what else could be done to satisfy the requirement, I only get boiler plate message above. Anyone know what they really looking for? Any insights is appreciated. Thanks!
1
0
156
1w
Guidance / Documentation on iOS 18.6.1 Blood Oxygen Saturation
Are there any HealthKit related changes to be aware of in the new update that enables SPO2 / Blood Oxygen Saturation measurements on certain Apple Watch models within the US? I’m aware of processing happening on the phone…. But beyond that: Does this mean values are then saved to Apple Health? Do these models still take background SPO2 measurements in the same way as other models do? Are these values then visible in third party iOS apps as normal through HealthKit? Do these values sync back to the paired Apple Watch HealthKit store for third party apps to access on the Watch? For reference I have an iOS and WatchOS app that, amongst other features, provides the ability to see your SPO2 values in the Watch app, complications and in the iOS app.
7
0
213
1w
What’s the expected frequency of HealthKit enableBackgroundDelivery: HKCategoryTypeIdentifier.sleepAnalysis
Hello, I have enabled HealthKit background delivery for sleep analysis samples: private func setupSleepDataBackgroundDelivery() { if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) { healthStore.enableBackgroundDelivery(for: sleepType, frequency: .immediate) { (success, error) in } } } In general, this function works. But I would love to know what the limitations / expected delivery delay for frequency: .immediate is. The documentation is only very vague about this and specifies that some sample types such as steps are only delivered once per hour. But how about sleep data? Is this expected to be delivered immediately once available on iPhone? Thanks a lot for your help!
2
2
204
2w
Sleep Score API access
New in iOS 26 and WatchOS 26 is a Sleep Score calculation for users based on Duration, Bedtime and Interruptions. Unfortunately I can't find any APIs for developers to tap into this metric. Yes, in theory it's all created off the same Sleep Analysis data already available with HealthKit but that makes it very hard to recreate in our apps. If the numbers don't match up exactly, users will understandably complain. Can anyone confirm that this is the case and I've not missed a Sleep Score API? I'll then file feedback. Hopefully this doesn't go the way of Heart Rate Zones where the Apple Watch iPhone app has generated them for years and provided no way for third party apps to access these values (yes many feedbacks provided previously).
3
1
184
3w
Best Practices for Continuous Background Biometric Monitoring on Apple Watch
Hello, everyone! I'm seeking some guidance on the App Store review process and technical best practices for a watchOS app. My goal is to create an app that uses HealthKit to continuously monitor a user's heart rate in the background for sessions lasting between 30 minutes and 3 hours. This app would not be a fitness or workout tracker. My primary question is about the best way to achieve this reliably while staying within the App Store Review Guidelines. Is it advisable to use the WorkoutKit framework to start a custom, non-fitness "session" for the purpose of continuous background monitoring? Are there any other recommended APIs or frameworks for this kind of background data collection on watchOS that I should be aware of? What are the key review considerations I should be mindful of, particularly regarding Guideline 4.1 (Design) and the intended use of APIs? My app's core functionality would require this kind of data for a beneficial purpose. I want to ensure my approach is technically sound and has the best chance of a successful review. Any insights or advice from developers who have experience with similar use cases would be incredibly helpful! Thank you!
1
0
279
Aug ’25
UIScene.ConnectionOptions.shouldHandleActiveWorkoutRecovery Missing?
According to the WWDC25 Presentation Track workouts with HealthKit on iOS and iPadOS, there is supposed to be a new property for restoring an active workout after a crash on iOS/iPadOS. The developer documentation also supports this. However, this property does not seem to exist in the latest Xcode 26 beta, even in projects targeting iOS 26.0 as the minimum version. Am I missing something? Has this property not been made available yet? It is actually looking like all of the new iOS 26.0 properties are missing UIScene.ConnectionOptions on my system.
3
0
145
Aug ’25
A Discussion on Marketing Sensitive Apps & Navigating App Review with a Privacy-First Approach
Hello everyone, Ujjwal here, founder and CEO of a new iOS app in the mental wellness space. Our mission is to provide accessible, AI-driven support for individuals dealing with anxiety, depression, and loneliness. From the very beginning, this has presented us with a unique and critical challenge: How do we effectively market an app to reach those who need it most, while upholding the absolute highest standards of user privacy? We've built our app, ThunDroid, with a "privacy-by-design" philosophy. We leverage on-device processing for our core AI features, utilize end-to-end encryption, and have proudly integrated 'Sign in with Apple' to maximize user anonymity. We believe these are not just features, but ethical obligations to our users, especially given the nature of the data they trust us with. The challenge, however, arises in marketing. This leads us to focus on mission-driven, organic marketing, but it's a slower path to reaching users who might be in immediate need of support. This brings me to my question for this knowledgeable community. What best practices or creative strategies have you found effective for marketing applications? I appreciate any insights or experiences you're willing to share as we continue to grow ThunDroid responsibly. Thank you for your time and consideration. App Store link: (would love to hear your reviews) [https://apps.apple.com/in/app/thundroid-ai-human-companion/id6746182736)
0
0
44
Jul ’25
Support for cycling power & cadence sensors in HKWorkoutSession on iOS?
Hi everyone, while testing HKWorkoutSession with HKLiveWorkoutBuilder on iOS 26 Beta (cycling workout), I noticed the following behavior: – Starting a cycling HKWorkoutSession automatically connects to my Bluetooth heart rate monitor and records HR into HealthKit ✅ – However, my Bluetooth cycling power meter and cadence sensor (standard BLE Cycling Power & CSC services) are not connected automatically, and no data is recorded into HealthKit ❌ On Apple Watch, when starting a cycling workout, these sensors do connect automatically and their data is written to HealthKit — which is exactly what I would expect on iOS as well. Question: Is this by design, or is support for power and cadence sensors planned for iOS in the same way as on watchOS? Or do we, as developers, need to implement the BLE Cycling Power and CSC profiles ourselves (via CoreBluetooth) if we want these metrics? Environment: – iOS 26 Beta – HKWorkoutSession & HKLiveWorkoutBuilder (cycling) – Bluetooth HRM connects automatically – BLE power & cadence sensors do not This feature would make it much easier to develop cycling apps with full HealthKit integration, and also create a more consistent user experience compared to watchOS. Thanks for any insights!
2
1
102
Jul ’25
HKLiveWorkoutBuilder get wrong calorie data for iOS 26
In iOS 26, HKLiveWorkoutBuilder is supported, which we can use like HKWorkoutSession in watchOS - this is very exciting. However, it currently seems to have a bug in calculating calories. I tested it in my app, and for nearly 6 minutes with an average heart rate of 134, it only calculated 8 calories consumed (80 calories per hour), including basal consumption, which is obviously incorrect. (I used Powerboats Pro 2 connected to my phone, which includes heart rate data, and HKLiveWorkoutBuilder correctly collected the heart rate, which is great.) I think my code is correct. func workoutBuilder(_ workoutBuilder: HKLiveWorkoutBuilder, didCollectDataOf collectedTypes: Set<HKSampleType>) { for type in collectedTypes { guard let quantityType = type as? HKQuantityType else { return // Nothing to do. } let statistics = workoutBuilder.statistics(for: quantityType) if let statistics = statistics { switch statistics.quantityType { case HKQuantityType.quantityType(forIdentifier: .heartRate): /// - Tag: SetLabel let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute()) let value = statistics.mostRecentQuantity()?.doubleValue(for: heartRateUnit) let roundedValue = Double( round( 1 * value! ) / 1 ) if let avg = statistics.averageQuantity()?.doubleValue(for: heartRateUnit) { self.avgHeartRate = avg } self.delegate?.didUpdateHeartBeat(self, heartBeat: Int(roundedValue)) case HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned): let energyUnit = HKUnit.kilocalorie() let value = statistics.sumQuantity()?.doubleValue(for: energyUnit) self.totalActiveEnergyBurned = Double(value!) print("didUpdate totalActiveEnergyBurned: \(self.totalActiveEnergyBurned)") self.delegate?.didUpdateEnergyBurned(self, totalEnergy: self.totalActiveEnergyBurned + self.totalBasalEneryBurned) return case HKQuantityType.quantityType(forIdentifier: .basalEnergyBurned): let energyUnit = HKUnit.kilocalorie() let value = statistics.sumQuantity()?.doubleValue(for: energyUnit) self.totalBasalEneryBurned = Double(value!) print("didUpdate totalBasalEneryBurned: \(self.totalBasalEneryBurned)") self.delegate?.didUpdateEnergyBurned(self, totalEnergy: self.totalActiveEnergyBurned + self.totalBasalEneryBurned) return default: print("unhandled quantityType=\(statistics.quantityType) when processing statistics") return } } I think I've found the source of the problem: let workoutConfiguration = HKWorkoutConfiguration() workoutConfiguration.activityType = .traditionalStrengthTraining //walking, running is ok workoutConfiguration.locationType = .outdoor When I set the activityType to walking or running, the calorie results are correct, showing several hundred calories per hour. However, when activityType is set to traditionalStrengthTraining or jumprope, the calculations are incorrect. PS: I'm currently using Xcode 26 beta3 and iOS 26 beta3. Hope this issue can be resolved. Thanks.
1
0
107
Jul ’25
Some swimming activities are not fetched by combined predicate
I'm using following filters to fetch swimming activities from HealthKit. For some users it fetches all workouts (pool && open water) but for other it skips some open water activities. See screenshot, all those swimming activities are not fetched by following code. let startDate = Calendar.current.date(byAdding: .month, value: -1, to: Date())! let endDate = Date() let swimmingPredicate = HKQuery.predicateForWorkouts(with: .swimming) let timePredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate) let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [swimmingPredicate, timePredicate]) let query = HKSampleQuery(sampleType: .workoutType(), predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [.init(keyPath: \HKSample.startDate, ascending: false)], resultsHandler: { [weak self] query, samples, error in ... Could someone help with ideads what is missing in this case?
0
0
49
Jul ’25
Workout Buddy not available
Has anyone seen the workout buddy options on watch OS yet? I am not able to get it on my watch. My setup is an iPhone 16 and Watch Ultra 1 with the 26 OS I am currently using beta 3. English US language on both and US as region. I am located in Germany though. I restarted both devices multiple times without any changes. Hopefully someone can help.
1
0
66
Jul ’25
Adding workoutEffortScore to HKWorkout
I'm trying to hook into the new workoutEffort score supported in iOS 18, I am collecting this information from users when they submit their workout and trying to add a sample to the HKWorkout in the same manner as I've been adding other samples like bodyweight, calories burned, etc. I'm receiving the error: HKWorkout: Sample of type HKQuantityTypeIdentifierWorkoutEffortScore must be related to a workout I tried adding the samples using HKWorkoutBuilder.add([samples]) as which has been working perfectly for calories burned & bodyweight, but I am receiving the above error for workoutEffortScore As a second approach, I tried adding the sample after I called finishWorkout on the HKWorkoutBuilder and received back the HKWorkout object using HKHealthStore.add([samples], to: HKWorkout) and am still receiving the same error! I don't know otherwise how to relate a sample to a workout, I thought those were the APIs to do so? I'm using Xcode 16.0 RC (16A242) and testing on an iOS 16 Pro simulator
5
1
1.4k
Jul ’25
HealthKit - HKWorkoutRouteBuilder never returns from insert when created from newly added iOS HKLiveWorkoutBuilder API on Simulator
Has anyone had success using the HKWorkoutRouteBuilder in conjunction with the new iOS support for HKLiveWorkoutBuilder? I was running my watchOS code that worked now brought over to iOS and when I call insertRouteData the function never returns. This happens for both the legacy and closure based block patterns. private var workoutSession: HKWorkoutSession? private var workoutBuilder: HKLiveWorkoutBuilder? private var serviceSession: CLServiceSession? private var workoutRouteBuilder: HKWorkoutRouteBuilder? private func startRouteBuilder() { Task { @MainActor in self.serviceSession = CLServiceSession(authorization: .whenInUse) self.workoutRouteBuilder = self.workoutBuilder?.seriesBuilder(for: .workoutRoute()) as? HKWorkoutRouteBuilder self.locationUpdateTask = Task { do { for try await update in CLLocationUpdate.liveUpdates(.fitness) { if let location = update.location { self.logger.notice(#function, metadata: [ "location": .stringConvertible(location) ]) try await self.workoutRouteBuilder?.insertRouteData([location]) self.logger.notice("Added location") } } } catch { self.logger.error(#function, metadata: [ "error": .stringConvertible(error.localizedDescription) ]) } } } } I did also try CLLocationManager API with delegate which is what my current watch code uses (a bit old). Same issue. Here is what I've found so far: If the workout session is not running, and if the builder hasn't started collection yet, inserting route data works just fine I've tried different swift language modes, flipped from main actor to non isolated project settings (Xcode 26) Modified Apple's sample code and added location route building to that and reproduced the error, modified sample attached to feedback This issue was identified against Xcode 26 beta 2 and iPhone 16 Pro simulator. Works as expected on my iPhone 13 Pro beta 2. FB18603581 - HealthKit: HKWorkoutRouteBuilder insert call within CLLocationUpdate task never returns
0
0
148
Jul ’25