Loading...
Loading...
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.
npx skill4agent add dpearson2699/swift-ios-skills healthkitNSHealthShareUsageDescriptionNSHealthUpdateUsageDescriptionimport HealthKit
let healthStore = HKHealthStore()
guard HKHealthStore.isHealthDataAvailable() else {
// HealthKit not available on this device (e.g., iPad)
return
}HKHealthStorefunc 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
)
}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
}HKSampleQueryDescriptorHKSampleQueryfunc 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)")
}HKStatisticsQueryDescriptorfunc 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())
}.cumulativeSum.discreteAverage.discreteMin.discreteMaxHKStatisticsCollectionQueryDescriptorfunc 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, value: -days, to: endDate)!
let predicate = HKQuery.predicateForSamples(
withStart: startDate, end: endDate
)
let stepType = HKQuantityType(.stepCount)
let samplePredicate = HKSamplePredicate.quantitySample(
type: stepType, predicate: predicate
)
let query = HKStatisticsCollectionQueryDescriptor(
predicate: samplePredicate,
options: .cumulativeSum,
anchorDate: endDate,
intervalComponents: DateComponents(day: 1)
)
let collection = try await query.result(for: healthStore)
var dailySteps: [(date: Date, steps: Double)] = []
collection.statisticsCollection.enumerateStatistics(
from: startDate, to: endDate
) { statistics, _ in
let steps = statistics.sumQuantity()?
.doubleValue(for: .count()) ?? 0
dailySteps.append((date: statistics.startDate, steps: steps))
}
return dailySteps
}results(for:)AsyncSequencelet updateStream = query.results(for: healthStore)
Task {
for try await result in updateStream {
// result.statisticsCollection contains updated data
}
}HKQuantitySamplefunc saveSteps(count: Double, start: Date, end: Date) async throws {
let stepType = HKQuantityType(.stepCount)
let quantity = HKQuantity(unit: .count(), doubleValue: count)
let sample = HKQuantitySample(
type: stepType,
quantity: quantity,
start: start,
end: end
)
try await healthStore.save(sample)
}
func enableStepCountBackgroundDelivery() async throws {
let stepType = HKQuantityType(.stepCount)
try await healthStore.enableBackgroundDelivery(
for: stepType,
frequency: .hourly
)
}HKObserverQuerylet observerQuery = HKObserverQuery(
sampleType: HKQuantityType(.stepCount),
predicate: nil
) { query, completionHandler, error in
defer { completionHandler() } // Must call to signal done
guard error == nil else { return }
// Fetch new data, update UI, etc.
}
healthStore.execute(observerQuery).immediate.hourly.daily.weeklyenableBackgroundDeliveryHKWorkoutSessionHKLiveWorkoutBuilderfunc startWorkout() async throws {
let configuration = HKWorkoutConfiguration()
configuration.activityType = .running
configuration.locationType = .outdoor
let session = try HKWorkoutSession(
healthStore: healthStore,
configuration: configuration
)
session.delegate = self
let builder = session.associatedWorkoutBuilder()
builder.dataSource = HKLiveWorkoutDataSource(
healthStore: healthStore,
workoutConfiguration: configuration
)
session.startActivity(with: Date())
try await builder.beginCollection(at: Date())
}
func endWorkout(
session: HKWorkoutSession,
builder: HKLiveWorkoutBuilder
) async throws {
session.end()
try await builder.endCollection(at: Date())
try await builder.finishWorkout()
}references/healthkit-patterns.md| Identifier | Category | Unit |
|---|---|---|
| Fitness | |
| Fitness | |
| Fitness | |
| Fitness | |
| Vitals | |
| Vitals | |
| Vitals | |
| Body | |
| Body | |
| Body | |
| Body | |
| Lab | |
.sleepAnalysis.mindfulSession.appleStandHour.dateOfBirth.biologicalSex.bloodType.fitzpatrickSkinType// Basic units
HKUnit.count() // Steps, counts
HKUnit.meter() // Distance
HKUnit.mile() // Distance (imperial)
HKUnit.kilocalorie() // Energy
HKUnit.joule(with: .kilo) // Energy (SI)
HKUnit.gramUnit(with: .kilo) // Mass (kg)
HKUnit.pound() // Mass (imperial)
HKUnit.percent() // Percentage
// Compound units
HKUnit.count().unitDivided(by: .minute()) // Heart rate (bpm)
HKUnit.meter().unitDivided(by: .second()) // Speed (m/s)
// Prefixed units
HKUnit.gramUnit(with: .milli) // Milligrams
HKUnit.literUnit(with: .deci) // Deciliters// App Review will reject this
let allTypes: Set<HKObjectType> = [
HKQuantityType(.stepCount),
HKQuantityType(.heartRate),
HKQuantityType(.bloodGlucose),
HKQuantityType(.bodyMass),
HKQuantityType(.oxygenSaturation),
// ...20 more types the app never uses
]let neededTypes: Set<HKObjectType> = [
HKQuantityType(.stepCount),
HKQuantityType(.activeEnergyBurned)
]func getSteps() async throws -> Double {
let result = try await query.result(for: healthStore)
return result!.sumQuantity()!.doubleValue(for: .count()) // Crashes if denied
}func getSteps() async throws -> Double {
let result = try await query.result(for: healthStore)
return result?.sumQuantity()?.doubleValue(for: .count()) ?? 0
}let store = HKHealthStore() // Crashes on iPad
try await store.requestAuthorization(toShare: types, read: types)guard HKHealthStore.isHealthDataAvailable() else {
showUnsupportedDeviceMessage()
return
}// Bad: HKSampleQuery with callback on main thread
// Good: async descriptor
func loadAllData() async throws -> [HKQuantitySample] {
let descriptor = HKSampleQueryDescriptor(
predicates: [.quantitySample(type: stepType)],
sortDescriptors: [SortDescriptor(\.endDate, order: .reverse)],
limit: 100
)
return try await descriptor.result(for: healthStore)
}let query = HKObserverQuery(sampleType: type, predicate: nil) { _, handler, _ in
processNewData()
// Forgot to call handler() -- system won't schedule next delivery
}let query = HKObserverQuery(sampleType: type, predicate: nil) { _, handler, _ in
defer { handler() }
processNewData()
}// Heart rate is discrete, not cumulative -- this returns nil
let query = HKStatisticsQueryDescriptor(
predicate: heartRatePredicate,
options: .cumulativeSum
)// Use discrete options for discrete types
let query = HKStatisticsQueryDescriptor(
predicate: heartRatePredicate,
options: .discreteAverage
)HKHealthStore.isHealthDataAvailable()Info.plistNSHealthShareUsageDescriptionNSHealthUpdateUsageDescriptionHKHealthStoreHKObserverQuerycompletionHandlerenableBackgroundDeliveryreferences/healthkit-patterns.md