home / skills / nonameplum / agent-skills / swift-health-kit

swift-health-kit skill

/swift-health-kit

This skill helps you integrate HealthKit data access and workflows across iPhone, Apple Watch, iPad, and visionOS.

npx playbooks add skill nonameplum/agent-skills --skill swift-health-kit

Review the files below or copy the command above to add this skill to your agents.

Files (3)
SKILL.md
5.8 KB
---
name: swift-health-kit
description: 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.
---

# 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

1. Add HealthKit capability in Xcode (enable Clinical Health Records only if needed).
2. Add `NSHealthShareUsageDescription` and `NSHealthUpdateUsageDescription` to Info.plist.
3. Check `HKHealthStore.isHealthDataAvailable()` before any HealthKit calls.
4. Create a single `HKHealthStore` instance and retain it for the app's lifetime.
5. Request authorization with `requestAuthorization(toShare:read:)` before reading or writing.

## Common workflows

### Reading data

1. Create the appropriate `HKSampleType` or `HKQuantityType`.
2. Build a query descriptor (e.g., `HKSampleQueryDescriptor`, `HKStatisticsQueryDescriptor`).
3. Execute the query against `HKHealthStore`.
4. Handle results on a background queue; dispatch to main for UI updates.

### Saving data

1. Create an `HKQuantitySample`, `HKCategorySample`, or `HKCorrelation`.
2. Use matching units for the data type (e.g., `.count()` for steps, `.meter()` for distance).
3. Call `healthStore.save(_:withCompletion:)`.
4. Check `authorizationStatus(for:)` before saving to catch permission issues early.

### Background delivery

1. Enable Background Modes in Xcode (Background fetch).
2. Call `enableBackgroundDelivery(for:frequency:withCompletion:)` for each data type.
3. Register an `HKObserverQuery` with an update handler.
4. When woken, call `healthStore.execute(_:)` to re-run the query.

### Workouts

1. Create an `HKWorkoutConfiguration` with activity type and location.
2. Start a workout session on Apple Watch with `HKWorkoutSession`.
3. Use `HKLiveWorkoutBuilder` to collect real-time samples.
4. 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:

```swift
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.

Overview

This skill provides a concise, practical guide to using Apple's HealthKit framework across iPhone, Apple Watch, iPad, and visionOS. It covers setup, authorization, reading and writing samples, workouts, observer queries, and background delivery. The content focuses on common workflows and key types so you can implement reliable health and fitness features quickly.

How this skill works

The skill walks through initializing and retaining a single HKHealthStore, requesting fine-grained authorizations, and executing queries and saves. It explains observer and anchored queries for change tracking, enabling background delivery, and using HKWorkoutSession and HKLiveWorkoutBuilder for real-time workout collection. Error cases, privacy constraints, and platform availability notes help you handle production scenarios.

When to use it

  • Integrating read/write access to steps, heart rate, sleep, or clinical records.
  • Building real-time workouts and activity ring integrations for watchOS and iPhone.
  • Implementing background delivery and observer queries to keep app data in sync.
  • Creating time-bucketed statistics or charts from HKStatisticsCollectionQuery.
  • Handling clinical records or visionOS guest-user restricted behavior.

Best practices

  • Add HealthKit capability and NSHealthShareUsageDescription/NSHealthUpdateUsageDescription to Info.plist before requesting access.
  • Check HKHealthStore.isHealthDataAvailable() and use a single HKHealthStore instance retained for the app lifetime.
  • Request authorization with requestAuthorization(toShare:read:) and inspect authorizationStatus(for:) before saves.
  • Execute queries on background queues and dispatch UI updates to the main queue.
  • Enable Background Modes and call enableBackgroundDelivery(...) combined with HKObserverQuery for reliable updates.
  • Respect privacy: never use HealthKit data for advertising or sell it; handle permission-denied flows gracefully.

Example use cases

  • Requesting step count and distance types, executing HKStatisticsQueryDescriptor for daily totals, and rendering activity rings.
  • Starting an HKWorkoutSession on Apple Watch, collecting samples with HKLiveWorkoutBuilder, and saving the HKWorkout at session end.
  • Using HKObserverQuery + enableBackgroundDelivery to react to new heart rate samples and refresh app state.
  • Running HKAnchoredObjectQueryDescriptor to sync additions and deletions since a stored anchor.
  • Requesting and displaying clinical records where available and handling required-authorization denial errors.

FAQ

What if HealthKit returns no data after authorization?

No data can mean the user denied read access or the device has no samples. Use authorizationStatus(for:) to check permissions and handle empty results as 'no permitted data' rather than an error.

How do I get background updates for new samples?

Enable Background Modes, register an HKObserverQuery with an update handler, and call enableBackgroundDelivery(for:frequency:withCompletion:) for each type. Re-run a read/anchored query when woken to fetch new data.