HealthKit
Access, query, and store health and fitness metrics in Apple Health using HealthKit. Covers authorization, quantity samples, statistics collection queries, background delivery, and workout sessions. Targets Swift 6.3 / iOS 26+.
Contents
Capabilities and Privacy
Enable HealthKit in Signing & Capabilities. If your app observes updates in the background, enable the Background Delivery checkbox.
Declare usage descriptions in Info.plist:
NSHealthShareUsageDescription: Required for reading health data.
NSHealthUpdateUsageDescription: Required for writing health data.
NSHealthClinicalHealthRecordsShareUsageDescription: Required if accessing clinical records.
[!IMPORTANT]
Request only the exact types needed for the immediate feature. App Review strictly rejects apps requesting unneeded health permissions.
Availability and HKHealthStore
Always guard initialization with HKHealthStore.isHealthDataAvailable(). HealthKit is supported on iPhone, Apple Watch, iPad (iPadOS 17+), and Vision Pro, but unavailable on iPadOS 16 or earlier and managed devices with restrictions.
guard HKHealthStore.isHealthDataAvailable() else { return }
let healthStore = HKHealthStore() // Single thread-safe shared store
Query Selection Matrix
| Query Type |
Best Used For |
Execution |
HKSampleQueryDescriptor |
Raw individual samples with sorting and limits |
One-shot async |
HKStatisticsQueryDescriptor |
Single aggregate metric (sum, average, min/max) over a date range |
One-shot async |
HKStatisticsCollectionQueryDescriptor |
Time-series aggregations (daily step charts, hourly heart rate) |
One-shot or continuous |
HKAnchoredObjectQueryDescriptor |
Incremental synchronization with anchor tokens |
One-shot or streaming |
HKObserverQuery |
Background delivery triggers when health data changes |
Background notification |
Writing Samples and Units
Always specify compatible HKUnits matching the quantity type. For cumulative metrics (steps, active energy), set start and end dates encompassing the measurement interval; for discrete metrics (heart rate), use identical start and end dates.
Route by Task
- For statistics collection queries and SwiftUI health chart configurations, read Statistics and Charts.
- For background observation and setting up
enableBackgroundDelivery, read Background Delivery.
- For recording live workouts with
HKWorkoutSession and HKLiveWorkoutBuilder, read Live Workout Sessions.
- For complete HKUnit string formats, conversion, and compound units, read HKUnit Reference.
Common Mistakes
- Calling HealthKit APIs without checking
HKHealthStore.isHealthDataAvailable().
- Missing
NSHealthShareUsageDescription or NSHealthUpdateUsageDescription, causing immediate crash on launch.
- Creating multiple
HKHealthStore instances instead of sharing a single instance across the app.
- Assuming read authorization can be inspected (Apple intentionally masks read authorization status for privacy).
- Using incompatible units (e.g. attempting to store step count with
.meter() instead of .count()).
Review Checklist
References
1---2name: healthkit3description: Builds HealthKit authorization, sample reads/writes, statistics, background delivery, and workout sessions. Use for Apple Health metrics, charts, HKQuantitySample storage, HKLiveWorkoutBuilder, unit handling, workout recording, or health-data delivery and privacy behavior.4---56# HealthKit78Access, query, and store health and fitness metrics in Apple Health using `HealthKit`. Covers authorization, quantity samples, statistics collection queries, background delivery, and workout sessions. Targets Swift 6.3 / iOS 26+.910## Contents1112- [Capabilities and Privacy](#capabilities-and-privacy)13- [Availability and HKHealthStore](#availability-and-hkhealthstore)14- [Query Selection Matrix](#query-selection-matrix)15- [Writing Samples and Units](#writing-samples-and-units)16- [Route by Task](#route-by-task)17- [Common Mistakes](#common-mistakes)18- [Review Checklist](#review-checklist)19- [References](#references)2021## Capabilities and Privacy2223Enable **HealthKit** in Signing & Capabilities. If your app observes updates in the background, enable the **Background Delivery** checkbox.2425Declare usage descriptions in `Info.plist`:26- `NSHealthShareUsageDescription`: Required for reading health data.27- `NSHealthUpdateUsageDescription`: Required for writing health data.28- `NSHealthClinicalHealthRecordsShareUsageDescription`: Required if accessing clinical records.2930> [!IMPORTANT]31> Request only the exact types needed for the immediate feature. App Review strictly rejects apps requesting unneeded health permissions.3233## Availability and HKHealthStore3435Always guard initialization with `HKHealthStore.isHealthDataAvailable()`. HealthKit is supported on iPhone, Apple Watch, iPad (iPadOS 17+), and Vision Pro, but unavailable on iPadOS 16 or earlier and managed devices with restrictions.3637```swift38guard HKHealthStore.isHealthDataAvailable() else { return }39let healthStore = HKHealthStore() // Single thread-safe shared store40```4142## Query Selection Matrix4344| Query Type | Best Used For | Execution |45|---|---|---|46| `HKSampleQueryDescriptor` | Raw individual samples with sorting and limits | One-shot async |47| `HKStatisticsQueryDescriptor` | Single aggregate metric (sum, average, min/max) over a date range | One-shot async |48| `HKStatisticsCollectionQueryDescriptor` | Time-series aggregations (daily step charts, hourly heart rate) | One-shot or continuous |49| `HKAnchoredObjectQueryDescriptor` | Incremental synchronization with anchor tokens | One-shot or streaming |50| `HKObserverQuery` | Background delivery triggers when health data changes | Background notification |5152## Writing Samples and Units5354Always specify compatible `HKUnit`s matching the quantity type. For cumulative metrics (steps, active energy), set start and end dates encompassing the measurement interval; for discrete metrics (heart rate), use identical start and end dates.5556## Route by Task5758- For statistics collection queries and SwiftUI health chart configurations, read [Statistics and Charts](references/healthkit-patterns.md#statistics-collection-queries).59- For background observation and setting up `enableBackgroundDelivery`, read [Background Delivery](references/healthkit-patterns.md#background-delivery).60- For recording live workouts with `HKWorkoutSession` and `HKLiveWorkoutBuilder`, read [Live Workout Sessions](references/healthkit-patterns.md#workout-sessions).61- For complete HKUnit string formats, conversion, and compound units, read [HKUnit Reference](references/healthkit-patterns.md#hkunit-reference).6263## Common Mistakes6465- Calling HealthKit APIs without checking `HKHealthStore.isHealthDataAvailable()`.66- Missing `NSHealthShareUsageDescription` or `NSHealthUpdateUsageDescription`, causing immediate crash on launch.67- Creating multiple `HKHealthStore` instances instead of sharing a single instance across the app.68- Assuming read authorization can be inspected (Apple intentionally masks read authorization status for privacy).69- Using incompatible units (e.g. attempting to store step count with `.meter()` instead of `.count()`).7071## Review Checklist7273- [ ] `HKHealthStore.isHealthDataAvailable()` checked before accessing store74- [ ] Info.plist contains both share and update descriptions75- [ ] HealthKit capability enabled in target signing76- [ ] Read and write authorization requested in separate explicit sets77- [ ] Unit matches target `HKQuantityType` dimension78- [ ] Background delivery enabled with `enableBackgroundDelivery(for:frequency:)`79- [ ] Queries use predicate intervals to prevent scanning full lifetime history80- [ ] UI gracefully handles devices where HealthKit is unavailable (e.g. iPadOS 16)8182## References8384- [HealthKit extended query patterns and workout builders](references/healthkit-patterns.md)85- [HealthKit documentation](https://sosumi.ai/documentation/healthkit)86- [HKHealthStore](https://sosumi.ai/documentation/healthkit/hkhealthstore)87- [HKQuantityType](https://sosumi.ai/documentation/healthkit/hkquantitytype)88- [HKWorkoutSession](https://sosumi.ai/documentation/healthkit/hkworkoutsession)