/healthkit
Read, write, and query Apple Health data using HealthKit. Covers HKHealthStore authorization, sample queries, statistics queries, statistics collection queries for charts, saving HKQuantitySample data, background delivery, workout sessions with HKWorkoutSession and
$ npx -y skills add dpearson2699/swift-ios-skills --skill healthkit --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
- Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
- You can call itInvoke it directly when you want it.
- Slash command
/healthkit
Context preview
The summary Claude sees to decide when to auto-load this skill.
Read, write, and query Apple Health data using HealthKit. Covers HKHealthStore authorization, sample queries, statistics queries, statistics collection queries for charts, saving HKQuantitySample data, background delivery, workout sessions with HKWorkoutSession and
SKILL.md
healthkit.SKILL.mdname: healthkit
description: "Read, write, and query Apple Health data using HealthKit. Covers HKHealthStore authorization, sample queries, statistics queries, statistics collection queries for charts, saving HKQuantitySample data, background delivery, workout sessions with HKWorkoutSession and HKLiveWorkoutBuilder, HKUnit, and HKQuantityTypeIdentifier values. Use when integrating with Apple Health, displaying health metrics, recording workouts, or enabling background health data delivery."
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](#setup-and-availability)
- [Authorization](#authorization)
- [Reading Data: Sample Queries](#reading-data-sample-queries)
- [Reading Data: Statistics Queries](#reading-data-statistics-queries)
- [Reading Data: Statistics Collection Queries](#reading-data-statistics-collection-queries)
- [Writing Data](#writing-data)
- [Background Delivery](#background-delivery)
- [Workout Sessions](#workout-sessions)
- [Common Data Types](#common-data-types)
- [HKUnit Reference](#hkunit-reference)
- [Common Mistakes](#common-mistakes)
- [Review Checklist](#review-checklist)
- [References](#references)
Setup and Availability
Project Configuration
1. Enable the HealthKit capability in Xcode (adds the entitlement) 2. Add `NSHealthShareUsageDescription` (read) and `NSHealthUpdateUsageDescription` (write) to Info.plist 3. 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.
import HealthKit
guard HKHealthStore.isHealthDataAvailable() else {
// Health data is unavailable or restricted on this device.
return
}
let healthStore = HKHealthStore()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.
func requestAuthorization() async throws {
let typesToShare: Set<HKSampleType> = [
HKQuantityType(.stepCount),
HKQuantityType(.activeEnergyBurned)
]
let typesToRead: Set<HKObjectType> = [
HKQuantityType(.stepCount),
HKQuantityType(.heartRate),
HKQuantityType(.activeEnergyBurned),
HKCharacteristicType(.dateOfBirth)
]
try await healthStore.requestAuthorization(
toShare: typesToShare,
read: typesToRead
)
}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.
let status = healthStore.authorizationStatus(
for: HKQuantityType(.stepCount)
)
switch status {
case .notDetermined:
// Haven't requested yet -- safe to call requestAuthorization
break
case .sharingAuthorized:
// User granted write access
break
case .sharingDenied:
// User denied write access (read denial is indistinguishable from "no data")
break
@unknown default:
break
}Reading Data: Sample Queries
Use `HKSampleQueryDescriptor` (async/await) for one-shot reads. Prefer descriptors over the older callback-based `HKSampleQuery`.
func fetchRecentHeartRates() async throws -> [HKQuantitySample] {
let heartRateType = HKQuantityType(.heartRate)
let descriptor = HKSampleQueryDescriptor(
predicates: [.quantitySample(type: heartRateType)],
sortDescriptors: [SortDescriptor(\.endDate, order: .reverse)],
limit: 20
)
let results = try await descriptor.result(for: healthStore)
return results
}
// Extracting values from samples:
for sample in results {
let bpm = sample.quantity.doubleValue(
for: HKUnit.count().unitDivided(by: .minute())
)
print("\(bpm) bpm at \(sample.endDate)")
}Reading Data: Statistics Queries
Use `HKStatisticsQueryDescriptor` for aggregated single-value stats (sum, average, min, max).
func fetchTodayStepCount() async throws -> Double? {
let calendar = Calendar.current
let startOfDay = calendar.startOfDay(for: Date())
let endOfDay = calendar.date(byAdding: .day, value: 1, to: startOfDay)!
let predicate = HKQuery.predicateForSamples(
withStart: startOfDay, end: endOfDay
)
let stepType = HKQuantityType(.stepCount)
let samplePredicate = HKSamplePredicate.quantitySample(
type: stepType, predicate: predicate
)
let query = HKStatisticsQueryDescriptor(
predicate: samplePredicate,
options: .cumulativeSum
)
let result = try await query.result(for: healthStore)
return result?.sumQuantity()?.doubleValue(for: .count())
}**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.
func fetchDailySteps(forLast days: Int) async throws -> [(date: Date, steps: Double)] {
let calendar = Calendar.current
let endDate = calendar.startOfDay(
for: calendar.date(byAdding: .day, value: 1, to: Date())!
)
let startDate = calendar.date(byAdding: .day,Read more
name: healthkit description: "Read, write, and query Apple Health data using HealthKit. Covers HKHealthStore authorization, sample queries, statistics queries, statistics collection queries for charts, saving HKQuantitySample data, background delivery, workout sessions with HKWorkoutSession and HKLiveWorkoutBuilder, HKUnit, and HKQuantityTypeIdentifier values. Use when integrating with Apple Health, displaying health metrics, recording workouts, or enabling background health data delivery."
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](#setup-and-availability)
- [Authorization](#authorization)
- [Reading Data: Sample Queries](#reading-data-sample-queries)
- [Reading Data: Statistics Queries](#reading-data-statistics-queries)
- [Reading Data: Statistics Collection Queries](#reading-data-statistics-collection-queries)
- [Writing Data](#writing-data)
- [Background Delivery](#background-delivery)
- [Workout Sessions](#workout-sessions)
- [Common Data Types](#common-data-types)
- [HKUnit Reference](#hkunit-reference)
- [Common Mistakes](#common-mistakes)
- [Review Checklist](#review-checklist)
- [References](#references)
Setup and Availability
Project Configuration
1. Enable the HealthKit capability in Xcode (adds the entitlement) 2. Add `NSHealthShareUsageDescription` (read) and `NSHealthUpdateUsageDescription` (write) to Info.plist 3. 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.
import HealthKit
guard HKHealthStore.isHealthDataAvailable() else {
// Health data is unavailable or restricted on this device.
return
}
let healthStore = HKHealthStore()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.
func requestAuthorization() async throws {
let typesToShare: Set<HKSampleType> = [
HKQuantityType(.stepCount),
HKQuantityType(.activeEnergyBurned)
]
let typesToRead: Set<HKObjectType> = [
HKQuantityType(.stepCount),
HKQuantityType(.heartRate),
HKQuantityType(.activeEnergyBurned),
HKCharacteristicType(.dateOfBirth)
]
try await healthStore.requestAuthorization(
toShare: typesToShare,
read: typesToRead
)
}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.
let status = healthStore.authorizationStatus(
for: HKQuantityType(.stepCount)
)
switch status {
case .notDetermined:
// Haven't requested yet -- safe to call requestAuthorization
break
case .sharingAuthorized:
// User granted write access
break
case .sharingDenied:
// User denied write access (read denial is indistinguishable from "no data")
break
@unknown default:
break
}Reading Data: Sample Queries
Use `HKSampleQueryDescriptor` (async/await) for one-shot reads. Prefer descriptors over the older callback-based `HKSampleQuery`.
func fetchRecentHeartRates() async throws -> [HKQuantitySample] {
let heartRateType = HKQuantityType(.heartRate)
let descriptor = HKSampleQueryDescriptor(
predicates: [.quantitySample(type: heartRateType)],
sortDescriptors: [SortDescriptor(\.endDate, order: .reverse)],
limit: 20
)
let results = try await descriptor.result(for: healthStore)
return results
}
// Extracting values from samples:
for sample in results {
let bpm = sample.quantity.doubleValue(
for: HKUnit.count().unitDivided(by: .minute())
)
print("\(bpm) bpm at \(sample.endDate)")
}Reading Data: Statistics Queries
Use `HKStatisticsQueryDescriptor` for aggregated single-value stats (sum, average, min, max).
func fetchTodayStepCount() async throws -> Double? {
let calendar = Calendar.current
let startOfDay = calendar.startOfDay(for: Date())
let endOfDay = calendar.date(byAdding: .day, value: 1, to: startOfDay)!
let predicate = HKQuery.predicateForSamples(
withStart: startOfDay, end: endOfDay
)
let stepType = HKQuantityType(.stepCount)
let samplePredicate = HKSamplePredicate.quantitySample(
type: stepType, predicate: predicate
)
let query = HKStatisticsQueryDescriptor(
predicate: samplePredicate,
options: .cumulativeSum
)
let result = try await query.result(for: healthStore)
return result?.sumQuantity()?.doubleValue(for: .count())
}**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.
func fetchDailySteps(forLast days: Int) async throws -> [(date: Date, steps: Double)] {
let calendar = Calendar.current
let endDate = calendar.startOfDay(
for: calendar.date(byAdding: .day, value: 1, to: Date())!
)
let startDate = calendar.date(byAdding: .day,86 agent skills optimized for iOS 26+ development with Swift 6.3 and modern Apple frameworks.
Repo: dpearson2699/swift-ios-skills
Other skills on swift-ios-skills.
- /accessorysetupkit
Discover and configure Bluetooth and Wi-Fi accessories using AccessorySetupKit. Use when presenting a privacy-preserving accessory picker, defining discovery descriptors for BLE or Wi-Fi devices, handling accessory session events, migrating from CoreBluetooth permission-based
Open skill - /activitykit
Implement, review, or improve Live Activities and Dynamic Island experiences in iOS apps using ActivityKit. Use when building real-time updating widgets for the Lock Screen and Dynamic Island — delivery tracking, sports scores, ride-sharing status, workout timers, media
Open skill - /adattributionkit
Measure ad effectiveness with privacy-preserving attribution using AdAttributionKit. Use when registering ad impressions, handling attribution postbacks, updating conversion values, implementing re-engagement attribution, configuring publisher or advertiser apps, or replacing
Open skill - /alarmkit
Implement AlarmKit alarms and countdown timers for iOS and iPadOS with Lock Screen, Dynamic Island, StandBy, and paired Apple Watch system UI. Covers AlarmManager scheduling, AlarmAttributes and AlarmPresentation, system Stop and AlarmButton secondary actions, authorization,
Open skill - /app-clips
Build iOS App Clips with invocation URLs, App Clip Codes, NFC, QR codes, Safari banners, Maps, Messages, target setup, App Store Connect experiences, size/capability constraints, NSUserActivity routing, SKOverlay promotion, App Group/keychain handoff, ephemeral notifications,
Open skill - /app-intents
Implement App Intents for Siri, Shortcuts, Spotlight, widgets, Control Center, and Apple Intelligence on iOS. Covers AppIntent actions, AppEntity and EntityQuery models, AppShortcutsProvider phrases, IndexedEntity Spotlight indexing, WidgetConfigurationIntent, SnippetIntent, and
Open skill

