HealthKit
Read and write health and fitness data from the Apple Health store. Covers authorization, queries, writing samples, background delivery, and workout sessions. Targets Swift 6.3 / iOS 26+.
Contents
- Setup and Availability
- Authorization
- Reading Data: Sample Queries
- Reading Data: Statistics Queries
- Reading Data: Statistics Collection Queries
- Writing Data
- Background Delivery
- Workout Sessions
- Common Data Types
- HKUnit Reference
- Common Mistakes
- Review Checklist
- References
Setup and Availability
Project Configuration
- Enable the HealthKit capability in Xcode (adds the entitlement)
- Add
NSHealthShareUsageDescription(read) andNSHealthUpdateUsageDescription(write) to Info.plist - For background delivery, enable the "Background Delivery" sub-capability
Availability Check
Always check availability before calling other HealthKit APIs. Health data is available on iOS, watchOS, visionOS, iPadOS 17+, and iOS apps running on Vision Pro. It is unavailable on iPadOS 16 or earlier and may be restricted by managed device policy.
Create a single HKHealthStore instance and reuse it throughout your app. It
is thread-safe. If HealthKit is optional, review Xcode's generated
UIRequiredDeviceCapabilities healthkit entry so unsupported devices are not
excluded unintentionally.
Authorization
Request only the types your app genuinely needs. App Review rejects apps that over-request.
Checking Authorization Status
authorizationStatus(for:) reports write/share authorization. HealthKit does
not reveal whether read permission was granted or denied. If the user denies
read access, queries return only samples your app successfully saved, which may
look like empty or partial data.
Reading Data: Sample Queries
Use HKSampleQueryDescriptor (async/await) for one-shot reads. Prefer descriptors over the older callback-based HKSampleQuery.
Reading Data: Statistics Queries
Use HKStatisticsQueryDescriptor for aggregated single-value stats (sum, average, min, max).
Options by data type:
- Cumulative types (steps, calories):
.cumulativeSum - Discrete types (heart rate, weight):
.discreteAverage,.discreteMin,.discreteMax
Reading Data: Statistics Collection Queries
Use HKStatisticsCollectionQueryDescriptor for time-series data grouped into intervals -- ideal for charts.
Long-Running Collection Query
Use results(for:) (plural) to get an AsyncSequence that emits updates as new data arrives:
Writing Data
Create HKQuantitySample objects and save them to the store.
Treat try await healthStore.save(sample) returning as the save success gate;
only then report success or advance app state. On failure, surface the error and
correct the known authorization, type, unit, duration, or input problem before
constructing another sample. A bounded query or inspection in the Health app is
useful as an integration-test check when persistence evidence is required, but
is not a mandatory production read after every save.
Your app can only delete samples it created. Samples from other apps or Apple Watch are read-only.
Background Delivery
Register for background updates so your app is launched when new data arrives. Requires the background delivery entitlement.
Pair with an HKObserverQuery to handle notifications. Always call the completion handler:
Frequencies: .immediate, .hourly, .daily, .weekly
Set up observer queries as soon as the app launches, then call
enableBackgroundDelivery once for the same sample type. The system persists
the registration, wakes the app at most once per requested frequency, and
enforces tighter caps for some types such as hourly step-count delivery on iOS.
Background delivery is not supported on Simulator; test it on device.
Workout Sessions
Use HKWorkoutSession and HKLiveWorkoutBuilder to track live workouts.
HKWorkoutSession is available on iOS/iPadOS 17+, visionOS 1+, and watchOS 2+.
HKLiveWorkoutBuilder is available on iOS/iPadOS 26+ and watchOS 5+, so gate
live-builder code if supporting older iOS/iPadOS releases.
On iPhone and iPad, live heart-rate collection requires a paired external heart rate sensor. Apple Watch sessions can collect high-frequency heart-rate data. For locked iPhone workouts, plan for the system's workout-data access flow before showing health metrics on the Lock Screen.
Do not call endCollection and finishWorkout immediately after requesting the
stop. Wait for the session delegate's .stopped transition, then await
builder.endCollection(at:) followed by builder.finishWorkout(). Report the
workout as saved and clear session state only after both operations return.
Handle each thrown error without blindly repeating teardown. A successful
finishWorkout() can return no workout object while the device is locked, so a
nil result alone is not failure.
For full workout lifecycle management including pause/resume, delegate handling, and multi-device mirroring, see references/healthkit-patterns.md [blocked].
Common Data Types
HKQuantityTypeIdentifier
HKCategoryTypeIdentifier
Common category types: .sleepAnalysis, .mindfulSession, .appleStandHour
HKCharacteristicType
Read-only user characteristics include .dateOfBirth, .biologicalSex,
.bloodType, .fitzpatrickSkinType, .wheelchairUse, and .activityMoveMode.
HKUnit Reference
Common Mistakes
- Over-requesting data types. Request only the read/write types the feature actually uses; broad HealthKit permission sheets are an App Review risk.
- Treating read authorization like write authorization. You can check
.sharingAuthorizedbefore saving, but read denial is privacy-protected and looks like app-owned-only, empty, or partial results. - Skipping
isHealthDataAvailable(). Check before HealthKit access and handle unavailable or restricted stores without crashing. - Using callback queries for new async code. Prefer async descriptors for one-shot reads and statistics, and keep broad queries off the main actor.
- Forgetting observer completion handlers. Always call the handler; missed completions can delay or stop future background deliveries.
- Assuming
.immediatemeans immediate. Background delivery is capped by the system and must be tested on device. - Using cumulative stats for discrete values. Match statistics options to the data type: cumulative sums for steps/energy, discrete average/min/max for heart rate, weight, and similar samples.
Review Checklist
-
HKHealthStore.isHealthDataAvailable()checked before any HealthKit access - Only necessary data types requested in authorization
-
Info.plistincludesNSHealthShareUsageDescriptionand/orNSHealthUpdateUsageDescription - HealthKit capability enabled in Xcode project
- Write authorization checked before saving; read denial handled as partial or empty query results
- Single
HKHealthStoreinstance reused (not created per query) - Async query descriptors used instead of callback-based queries
- Heavy queries not blocking main thread
- Statistics options match data type (cumulative vs. discrete)
- Background delivery paired with app-launch
HKObserverQuerysetup andcompletionHandlercalled - Background delivery entitlement enabled if using
enableBackgroundDelivery - Background delivery tested on device and frequency caps considered
- Workout stop waits for the delegate's
.stoppedtransition beforeendCollectionandfinishWorkout; state clears only after successful finalization - Workout API availability and live heart-rate sensor requirements handled
- Delete operations target only objects the app previously saved
References
- Extended patterns (workouts, anchored queries, SwiftUI integration): references/healthkit-patterns.md [blocked]
- HealthKit framework
- HKHealthStore
- HKSampleQueryDescriptor
- HKStatisticsQueryDescriptor
- HKStatisticsCollectionQueryDescriptor
- HKWorkoutSession
- HKLiveWorkoutBuilder
- Setting up HealthKit
- Authorizing access to health data
- Configuring HealthKit access


