HealthKit
What to open
- Use
Articles/healtkit.md for complete HealthKit documentation (188 pages consolidated).
- Search within the file by section URLs or keywords like
HKHealthStore, HKQuantitySample, HKWorkout, HKObserverQuery.
Document structure
The documentation file is organized by Apple documentation URLs as section headers. Key sections:
| Line |
Topic |
| ~11 |
Framework overview |
| ~115 |
About the HealthKit framework (architecture) |
| ~246 |
Setting up HealthKit (entitlements, Info.plist) |
| ~357 |
Authorizing access to health data |
| ~517 |
Protecting user privacy |
| ~586 |
Saving data to HealthKit |
| ~673 |
Reading data from HealthKit (queries) |
| ~760 |
HKHealthStore API reference |
| ~968 |
Creating a Mobility Health App (sample project) |
| ~1025 |
Data types (type identifiers) |
| ~1614 |
Samples (HKSample, quantity, category, correlations) |
| ~1871 |
Queries (sample, anchored, statistics, observer) |
| ~2146 |
Visualizing State of Mind in visionOS |
| ~2203 |
Logging symptoms associated with a medication |
| ~2278 |
Workouts and activity rings |
| ~2449 |
HKError and error handling |
| ~3152 |
Executing observer queries |
| ~4778 |
Background delivery (HKUpdateFrequency) |
| ~5974 |
HKObjectType and subclasses |
| ~7264 |
HKSampleType reference |
Setup checklist
- Add HealthKit capability in Xcode (enable Clinical Health Records only if needed).
- Add
NSHealthShareUsageDescription and NSHealthUpdateUsageDescription to Info.plist.
- Check
HKHealthStore.isHealthDataAvailable() before any HealthKit calls.
- Create a single
HKHealthStore instance and retain it for the app's lifetime.
- Request authorization with
requestAuthorization(toShare:read:) before reading or writing.
Common workflows
Reading data
- Create the appropriate
HKSampleType or HKQuantityType.
- Build a query descriptor (e.g.,
HKSampleQueryDescriptor, HKStatisticsQueryDescriptor).
- Execute the query against
HKHealthStore.
- Handle results on a background queue; dispatch to main for UI updates.
Saving data
- Create an
HKQuantitySample, HKCategorySample, or HKCorrelation.
- Use matching units for the data type (e.g.,
.count() for steps, .meter() for distance).
- Call
healthStore.save(_:withCompletion:).
- Check
authorizationStatus(for:) before saving to catch permission issues early.
Background delivery
- Enable Background Modes in Xcode (Background fetch).
- Call
enableBackgroundDelivery(for:frequency:withCompletion:) for each data type.
- Register an
HKObserverQuery with an update handler.
- When woken, call
healthStore.execute(_:) to re-run the query.
Workouts
- Create an
HKWorkoutConfiguration with activity type and location.
- Start a workout session on Apple Watch with
HKWorkoutSession.
- Use
HKLiveWorkoutBuilder to collect real-time samples.
- End the session and save the workout with
endCollection(withEnd:completion:).
Key types
| Type |
Purpose |
HKHealthStore |
Central access point; authorization, queries, saving |
HKQuantitySample |
Numeric health data (steps, heart rate, weight) |
HKCategorySample |
Enumerated data (sleep analysis, menstrual flow) |
HKCorrelation |
Composite samples (food, blood pressure) |
HKWorkout |
Fitness activity with duration, energy, distance |
HKObserverQuery |
Long-running query for store changes |
HKAnchoredObjectQueryDescriptor |
Track additions/deletions since last anchor |
HKStatisticsQueryDescriptor |
Aggregate calculations (sum, avg, min, max) |
HKStatisticsCollectionQueryDescriptor |
Time-bucketed statistics for charts |
Privacy and authorization
- HealthKit uses fine-grained authorization per data type.
- Apps cannot detect if read permission was denied; queries simply return no data.
- Use
authorizationStatus(for:) to check write permission before saving.
- Guest User sessions on visionOS restrict mutations; handle
errorNotPermissibleForGuestUserMode.
- Never use HealthKit data for advertising or sell it to third parties.
Platform availability
- iPhone/Apple Watch/visionOS: Full HealthKit store with sync.
- iPadOS 17+: Has its own HealthKit store.
- iPadOS 16 and earlier / macOS 13+: Framework available but
isHealthDataAvailable() returns false.
- Use
earliestPermittedSampleDate() on Apple Watch to find oldest available data.
Error handling
Check for these common HKError.Code values:
errorHealthDataUnavailable – Device doesn't support HealthKit.
errorHealthDataRestricted – Enterprise or parental restrictions.
errorAuthorizationNotDetermined – Authorization not yet requested.
errorAuthorizationDenied – User denied write permission.
errorNotPermissibleForGuestUserMode – Vision Pro guest session restriction.
errorRequiredAuthorizationDenied – Required clinical record types denied.
SwiftUI integration
Use the HealthKitUI framework for SwiftUI authorization:
import HealthKitUI
.healthDataAccessRequest(
store: healthStore,
shareTypes: allTypes,
readTypes: allTypes,
trigger: trigger
) { result in
// Handle authorization result
}
Reminders
- HealthKit store is thread-safe; samples are immutable.
- Avoid samples longer than 24 hours; many types have duration limits.
- Correlations store contained samples internally—don't save them separately.
- Use
HKDeletedObject via anchored queries to detect deletions.
- For workout heart rate zones, use
HKWorkoutActivity and route samples.
1---2name: swift-health-kit3description: Apple HealthKit framework for health and fitness data. Use for reading/writing health samples, workout data, authorization flows, observer queries, background delivery, clinical records, activity rings, and integrating with the Health app across iPhone, Apple Watch, iPad, and visionOS.4---56# HealthKit78## What to open910- Use `Articles/healtkit.md` for complete HealthKit documentation (188 pages consolidated).11- Search within the file by section URLs or keywords like `HKHealthStore`, `HKQuantitySample`, `HKWorkout`, `HKObserverQuery`.1213## Document structure1415The documentation file is organized by Apple documentation URLs as section headers. Key sections:1617| Line | Topic |18|------|-------|19| ~11 | Framework overview |20| ~115 | About the HealthKit framework (architecture) |21| ~246 | Setting up HealthKit (entitlements, Info.plist) |22| ~357 | Authorizing access to health data |23| ~517 | Protecting user privacy |24| ~586 | Saving data to HealthKit |25| ~673 | Reading data from HealthKit (queries) |26| ~760 | HKHealthStore API reference |27| ~968 | Creating a Mobility Health App (sample project) |28| ~1025 | Data types (type identifiers) |29| ~1614 | Samples (HKSample, quantity, category, correlations) |30| ~1871 | Queries (sample, anchored, statistics, observer) |31| ~2146 | Visualizing State of Mind in visionOS |32| ~2203 | Logging symptoms associated with a medication |33| ~2278 | Workouts and activity rings |34| ~2449 | HKError and error handling |35| ~3152 | Executing observer queries |36| ~4778 | Background delivery (HKUpdateFrequency) |37| ~5974 | HKObjectType and subclasses |38| ~7264 | HKSampleType reference |3940## Setup checklist41421. Add HealthKit capability in Xcode (enable Clinical Health Records only if needed).432. Add `NSHealthShareUsageDescription` and `NSHealthUpdateUsageDescription` to Info.plist.443. Check `HKHealthStore.isHealthDataAvailable()` before any HealthKit calls.454. Create a single `HKHealthStore` instance and retain it for the app's lifetime.465. Request authorization with `requestAuthorization(toShare:read:)` before reading or writing.4748## Common workflows4950### Reading data51521. Create the appropriate `HKSampleType` or `HKQuantityType`.532. Build a query descriptor (e.g., `HKSampleQueryDescriptor`, `HKStatisticsQueryDescriptor`).543. Execute the query against `HKHealthStore`.554. Handle results on a background queue; dispatch to main for UI updates.5657### Saving data58591. Create an `HKQuantitySample`, `HKCategorySample`, or `HKCorrelation`.602. Use matching units for the data type (e.g., `.count()` for steps, `.meter()` for distance).613. Call `healthStore.save(_:withCompletion:)`.624. Check `authorizationStatus(for:)` before saving to catch permission issues early.6364### Background delivery65661. Enable Background Modes in Xcode (Background fetch).672. Call `enableBackgroundDelivery(for:frequency:withCompletion:)` for each data type.683. Register an `HKObserverQuery` with an update handler.694. When woken, call `healthStore.execute(_:)` to re-run the query.7071### Workouts72731. Create an `HKWorkoutConfiguration` with activity type and location.742. Start a workout session on Apple Watch with `HKWorkoutSession`.753. Use `HKLiveWorkoutBuilder` to collect real-time samples.764. End the session and save the workout with `endCollection(withEnd:completion:)`.7778## Key types7980| Type | Purpose |81|------|---------|82| `HKHealthStore` | Central access point; authorization, queries, saving |83| `HKQuantitySample` | Numeric health data (steps, heart rate, weight) |84| `HKCategorySample` | Enumerated data (sleep analysis, menstrual flow) |85| `HKCorrelation` | Composite samples (food, blood pressure) |86| `HKWorkout` | Fitness activity with duration, energy, distance |87| `HKObserverQuery` | Long-running query for store changes |88| `HKAnchoredObjectQueryDescriptor` | Track additions/deletions since last anchor |89| `HKStatisticsQueryDescriptor` | Aggregate calculations (sum, avg, min, max) |90| `HKStatisticsCollectionQueryDescriptor` | Time-bucketed statistics for charts |9192## Privacy and authorization9394- HealthKit uses fine-grained authorization per data type.95- Apps cannot detect if read permission was denied; queries simply return no data.96- Use `authorizationStatus(for:)` to check write permission before saving.97- Guest User sessions on visionOS restrict mutations; handle `errorNotPermissibleForGuestUserMode`.98- Never use HealthKit data for advertising or sell it to third parties.99100## Platform availability101102- **iPhone/Apple Watch/visionOS**: Full HealthKit store with sync.103- **iPadOS 17+**: Has its own HealthKit store.104- **iPadOS 16 and earlier / macOS 13+**: Framework available but `isHealthDataAvailable()` returns `false`.105- Use `earliestPermittedSampleDate()` on Apple Watch to find oldest available data.106107## Error handling108109Check for these common `HKError.Code` values:110111- `errorHealthDataUnavailable` – Device doesn't support HealthKit.112- `errorHealthDataRestricted` – Enterprise or parental restrictions.113- `errorAuthorizationNotDetermined` – Authorization not yet requested.114- `errorAuthorizationDenied` – User denied write permission.115- `errorNotPermissibleForGuestUserMode` – Vision Pro guest session restriction.116- `errorRequiredAuthorizationDenied` – Required clinical record types denied.117118## SwiftUI integration119120Use the `HealthKitUI` framework for SwiftUI authorization:121122```swift123import HealthKitUI124125.healthDataAccessRequest(126 store: healthStore,127 shareTypes: allTypes,128 readTypes: allTypes,129 trigger: trigger130) { result in131 // Handle authorization result132}133```134135## Reminders136137- HealthKit store is thread-safe; samples are immutable.138- Avoid samples longer than 24 hours; many types have duration limits.139- Correlations store contained samples internally—don't save them separately.140- Use `HKDeletedObject` via anchored queries to detect deletions.141- For workout heart rate zones, use `HKWorkoutActivity` and route samples.