
Healthkit
- 431 installs
- 297 repo stars
- Updated August 4, 2026
- vabole/apple-skills
healthkit is an Apple-skills agent skill that implements HealthKit read and write access, permissions, background delivery, and workout or vitals sync for iOS and watchOS developers.
About
healthkit is a skill from vabole/apple-skills guiding developers through Apple HealthKit integration on iOS and watchOS. It covers requesting and handling health data permissions, configuring read and write types, enabling background delivery for workouts and vitals, and syncing health samples between iPhone and Apple Watch targets. Engineers reach for healthkit when adding step counts, heart rate, workout sessions, or clinical vitals to a SwiftUI or UIKit app without reverse-engineering entitlement and privacy plist requirements. The skill targets native Apple platform APIs rather than cross-platform health bridges.
- HealthKit authorization and privacy prompts
- Background observers and anchored queries
- Workout, vitals, and clinical record patterns
- watchOS and iPhone data sharing
- App Store health data compliance
Healthkit by the numbers
- 431 all-time installs (skills.sh)
- +11 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #328 of 1,039 Mobile Development skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/vabole/apple-skills --skill healthkitAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 431 |
|---|---|
| repo stars | ★ 297 |
| Last updated | August 4, 2026 |
| Repository | vabole/apple-skills ↗ |
How do you implement HealthKit permissions in iOS?
Implement Apple HealthKit read/write, permissions, background delivery, and workout or vitals sync in iOS and watchOS apps.
Who is it for?
iOS and watchOS developers adding HealthKit read/write, background updates, or workout and vitals synchronization to Apple platform apps.
Skip if: Android Health Connect integrations, server-side FHIR pipelines, or apps that do not need on-device Apple health data.
When should I use this skill?
A user asks to add HealthKit, request health permissions, sync workouts or vitals, or enable background health delivery on iOS or watchOS.
What you get
HealthKit entitlements, permission flows, background delivery handlers, and workout or vitals sync code for iOS and watchOS.
- HealthKit integration code
- permission flows
- background delivery handlers
Files
HealthKit Documentation
Search these docs to answer questions about HealthKit APIs.
Return Format
Always include: 1. Summary - Answer the question concisely 2. File paths - List relevant files for full details, e.g.:
hkhealthstore.mdfor HKHealthStore APIhkunit.mdfor unit conversions
Files
healthkit-index.md- Framework overview and all available APIshkhealthstore.md- Health data store operationshkquantitysample.md- Quantity samples (weight, heart rate, etc.)hkquantitytypeidentifier.md- All quantity type identifiershksamplequery.md- Querying health datahkunit.md- Units and conversions
Navigation: HealthKit
Class
HKHealthStore
Available on: iOS 8.0+, iPadOS 8.0+, Mac Catalyst 13.0+, macOS 13.0+, visionOS 1.0+, watchOS 2.0+
The access point for all data managed by HealthKit.
class HKHealthStoreOverview
Use a HKHealthStore object to request permission to share or read HealthKit data. After you have permission, you can use the HealthKit store to save new samples to the store, or to manage the samples that your app saved. Additionally, you can use the HealthKit store to start, stop, and manage queries.
For more information, see Setting up HealthKit.
Inherits From
Conforms To
- CVarArg
- CustomDebugStringConvertible
- CustomStringConvertible
- Equatable
- Hashable
- NSObjectProtocol
- Sendable
- SendableMetatype
Accessing HealthKit
- authorizationStatus(for:)) Returns the app’s authorization status for sharing the specified data type.
- HKAuthorizationStatus Constants indicating the authorization status for a particular data type.
- getRequestStatusForAuthorization(toShare:read:completion:)) Indicates whether the system presents the user with a permission sheet if your app requests authorization for the provided types.
- HKAuthorizationRequestStatus Values that indicate whether your app needs to request authorization from the user.
- isHealthDataAvailable()) Returns a Boolean value that indicates whether HealthKit is available on this device.
- supportsHealthRecords()) Returns a Boolean value that indicates whether the current device supports clinical records.
- requestAuthorization(toShare:read:completion:)) Requests permission to save and read the specified data types.
- requestAuthorization(toShare:read:)) Asynchronously requests permission to save and read the specified data types.
- requestPerObjectReadAuthorization(for:predicate:completion:)) Asynchronously requests permission to read a data type that requires per-object authorization (such as vision prescriptions).
- handleAuthorizationForExtension(completion:)) Requests permission to save and read the data types specified by an extension.
- authorizationViewControllerPresenter The view controller that presents HealthKit authorization sheets.
Querying HealthKit data
- execute(_:)) Starts executing the provided query.
- stop(_:)) Stops a long-running query.
Reading characteristic data
- biologicalSex()) Reads someone’s biological sex from the HealthKit store.
- bloodType()) Reads the user’s blood type from the HealthKit store.
- dateOfBirth()) Reads the user’s date of birth from the HealthKit store as a date value.
- dateOfBirthComponents()) Reads the user’s date of birth from the HealthKit store as date components.
- fitzpatrickSkinType()) Reads the user’s Fitzpatrick Skin Type from the HealthKit store.
- wheelchairUse()) Reads the user’s wheelchair use from the HealthKit store.
Working with HealthKit objects
- delete(_:withCompletion:)-78l1m) Deletes the specified object from the HealthKit store.
- delete(_:withCompletion:)-17hzm) Deletes the specified objects from the HealthKit store.
- deleteObjects(of:predicate:withCompletion:)) Deletes objects saved by this application that match the provided type and predicate.
- earliestPermittedSampleDate()) Returns the earliest date permitted for samples.
- save(_:withCompletion:)-6fmtg) Saves the provided object to the HealthKit store.
- save(_:withCompletion:)-47iwb) Saves an array of objects to the HealthKit store.
Accessing the preferred units
- preferredUnits(for:completion:)) Returns the user’s preferred units for the given quantity types.
- HKUserPreferencesDidChange Notifies observers whenever the user changes his or her preferred units.
Managing background delivery
- enableBackgroundDelivery(for:frequency:withCompletion:)) Enables the delivery of updates to an app running in the background.
- com.apple.developer.healthkit.background-delivery A Boolean value that indicates whether observer queries receive updates while running in the background.
- HKUpdateFrequency Constants that determine how often the system launches your app in response to changes to HealthKit data.
- disableBackgroundDelivery(for:withCompletion:)) Disables background deliveries of update notifications for the specified data type.
- disableAllBackgroundDelivery(completion:)) Disables all background deliveries of update notifications.
Managing workouts
- splitTotalEnergy(_:start:end:resultsHandler:)) Calculates the active and resting energy burned based on the total energy burned over the given duration.
- recoverActiveWorkoutSession(completion:)) Recovers an active workout session.
Managing workout sessions
- workoutSessionMirroringStartHandler A block that the system calls when it starts a mirrored workout session.
- startWatchApp(with:completion:)) Launches or wakes the companion watchOS app to create a new workout session.
- pause(_:)) Pauses the provided workout session.
- resumeWorkoutSession(_:)) Resumes the provided workout session.
Managing estimates
- recalibrateEstimates(sampleType:date:completion:)) Recalibrates the prediction algorithm used to calculate the specified sample type.
Accessing the move mode
- activityMoveMode()) Returns the activity move mode for the current user.
- HKUserPreferencesDidChange Notifies observers whenever the user changes his or her preferred units.
Deprecated symbols
- add(_:to:completion:)) Associates the provided samples with the specified workout.
- start(_:)) Starts a workout session for the current app.
- end(_:)) Ends a workout session for the current app.
Structures
Instance Methods
- relateWorkoutEffortSample(_:with:activity:completion:))
- unrelateWorkoutEffortSample(_:from:activity:completion:))
Health data
- Saving data to HealthKit Create and share HealthKit samples.
- Reading data from HealthKit Use queries to request sample data from HealthKit.
- Creating a Mobility Health App Create a health app that allows a clinical care team to send and receive mobility data.
- Data types Specify the kind of data used in HealthKit.
- Samples Create and save health and fitness samples.
- Queries Query health and fitness data.
- Visualizing HealthKit State of Mind in visionOS Incorporate HealthKit State of Mind into your app and visualize the data in visionOS.
- Logging symptoms associated with a medication Fetch medications and dose events from the HealthKit store, and create symptom samples to associate with them.
---
Extracted from Apple DocC JSON by apple-skills tooling. This is unofficial content. All documentation belongs to Apple Inc.
Navigation: HealthKit
Class
HKQuantitySample
Available on: iOS 8.0+, iPadOS 8.0+, Mac Catalyst 13.0+, macOS 13.0+, visionOS 1.0+, watchOS 2.0+
A sample that represents a quantity, including the value and the units.
class HKQuantitySampleOverview
A quantity sample contains one or more HKQuantity objects. Each quantity represents a single piece of data with a single numeric value and the value’s associated units. For example, you can use quantity samples to record the user’s height, the user’s current heart rate, or the number of calories in a hamburger. HealthKit provides a wide range of quantity types, letting you track many different health and fitness features.
The HKQuantitySample class is a subclass of the HKSample class. Quantity samples are immutable; you set the sample’s properties when you create it, and they cannot change.
In iOS 13 and later and watchOS 6 and later, HKQuantitySample is an abstract superclass for the HKCumulativeQuantitySample and HKDiscreteQuantitySample concrete subclasses. The system automatically selects the correct subclass based on the HKQuantityType object used to create the sample.
Extend Quantity Samples
Like many HealthKit classes, you should not subclass the HKQuantitySample class. You may extend this class by adding metadata with custom keys to save related data used by your app.
For more information, see init(type:quantity:start:end:metadata:)).
Inherits From
Inherited By
Conforms To
- CVarArg
- CustomDebugStringConvertible
- CustomStringConvertible
- Equatable
- Hashable
- NSCoding
- NSObjectProtocol
- NSSecureCoding
- Sendable
- SendableMetatype
Creating Quantity Samples
- init(type:quantity:start:end:)) Returns a sample containing a numeric measurement.
- init(type:quantity:start:end:metadata:)) Returns a sample containing a numeric measurement with the provided metadata.
- init(type:quantity:start:end:device:metadata:)) Returns a sample containing a numeric measurement with the provided device and metadata.
Getting Property Data
- quantity The quantity for this sample.
- count The number of quantities contained in this sample.
- quantityType The quantity type for this sample.
Specifying Predicate Key Paths
- HKPredicateKeyPathQuantity The key path for accessing the sample’s quantity.
- HKPredicateKeyPathCount A key path for the sample’s count.
Initializers
- init(type:quantity:startDate:endDate:))
- init(type:quantity:startDate:endDate:device:metadata:))
- init(type:quantity:startDate:endDate:metadata:))
Basic samples
- HKCumulativeQuantitySample A sample that represents a cumulative quantity.
- HKDiscreteQuantitySample A sample that represents a discrete quantity.
- HKCategorySample A sample with values from a short list of possible values.
- HKCorrelation A sample that groups multiple related samples into a single entry.
- Units and quantities Objects used to specify a quantity for a given unit, and to convert between units.
- Metadata Keys Constants used to add metadata to objects stored in HealthKit.
---
Extracted from Apple DocC JSON by apple-skills tooling. This is unofficial content. All documentation belongs to Apple Inc.
Navigation: HealthKit
Structure
HKQuantityTypeIdentifier
Available on: iOS, iPadOS, Mac Catalyst, macOS, visionOS, watchOS
The identifiers that create quantity type objects.
struct HKQuantityTypeIdentifierOverview
To create an HKQuantityType instance, pass an HKQuantityTypeIdentifier value to the quantityType(forIdentifier:)) method.
Conforms To
Activity
- stepCount A quantity sample type that measures the number of steps the user has taken.
- distanceWalkingRunning A quantity sample type that measures the distance the user has moved by walking or running.
- runningGroundContactTime A quantity sample type that measures the amount of time the runner’s foot is in contact with the ground while running.
- runningPower A quantity sample type that measures the rate of work required for the runner to maintain their speed.
- runningSpeed A quantity sample type that measures the runner’s speed.
- runningStrideLength A quantity sample type that measures the distance covered by a single step while running.
- runningVerticalOscillation A quantity sample type measuring pelvis vertical range of motion during a single running stride.
- distanceCycling A quantity sample type that measures the distance the user has moved by cycling.
- pushCount A quantity sample type that measures the number of pushes that the user has performed while using a wheelchair.
- distanceWheelchair A quantity sample type that measures the distance the user has moved using a wheelchair.
- swimmingStrokeCount A quantity sample type that measures the number of strokes performed while swimming.
- distanceSwimming A quantity sample type that measures the distance the user has moved while swimming.
- distanceDownhillSnowSports A quantity sample type that measures the distance the user has traveled while skiing or snowboarding.
- basalEnergyBurned A quantity sample type that measures the resting energy burned by the user.
- activeEnergyBurned A quantity sample type that measures the amount of active energy the user has burned.
- flightsClimbed A quantity sample type that measures the number flights of stairs that the user has climbed.
- nikeFuel A quantity sample type that measures the number of NikeFuel points the user has earned.
- appleExerciseTime A quantity sample type that measures the amount of time the user spent exercising.
- appleMoveTime A quantity sample type that measures the amount of time the user has spent performing activities that involve full-body movements during the specified day.
- appleStandTime A quantity sample type that measures the amount of time the user has spent standing.
- vo2Max A quantity sample that measures the maximal oxygen consumption during exercise.
- crossCountrySkiingSpeed A quantity sample type that measures how fast you are traveling while cross country skiing.
- cyclingCadence A quantity sample type that represents the rate at which the user is pedaling.
- cyclingFunctionalThresholdPower A quantity sample type that measures the estimated maximum average power sustained while riding a bike for 60 minutes.
- cyclingPower A quantity sample type that measures the estimated power being used while riding a bike.
- cyclingSpeed A quantity sample type that measures how fast you are traveling while riding a bike.
- distanceCrossCountrySkiing A quantity sample type that measures the distance the user has moved by cross country skiing.
- distancePaddleSports A quantity sample type that measures the distance the user has moved by paddling sports.
- distanceRowing A quantity sample type that measures the distance the user has moved by rowing.
- distanceSkatingSports A quantity sample type that measures the distance the user has moved by skating.
- estimatedWorkoutEffortScore
- paddleSportsSpeed A quantity sample type that measures the distance the user has moved by paddling sports.
- physicalEffort A quantity sample type that measures the estimated amount of energy being used to perform a task excluding other factors such as temperature, altitude, or heart rate.
- rowingSpeed A quantity sample type that measures how fast the rower is moving.
- workoutEffortScore
Body measurements
- height A quantity sample type that measures the user’s height.
- bodyMass A quantity sample type that measures the user’s weight.
- bodyMassIndex A quantity sample type that measures the user’s body mass index.
- leanBodyMass A quantity sample type that measures the user’s lean body mass.
- bodyFatPercentage A quantity sample type that measures the user’s body fat percentage.
- waistCircumference A quantity sample type that measures the user’s waist circumference.
- appleSleepingWristTemperature A quantity sample type that records the wrist temperature during sleep.
Reproductive health
- basalBodyTemperature A quantity sample type that records the user’s basal body temperature.
Hearing
- environmentalAudioExposure A quantity sample type that measures audio exposure to sounds in the environment.
- environmentalSoundReduction A quantity sample type that measures the difference in sound intensity when wearing headphones that lower environmental sound levels.
- headphoneAudioExposure A quantity sample type that measures audio exposure from headphones.
Vital signs
- heartRate A quantity sample type that measures the user’s heart rate.
- restingHeartRate A quantity sample type that measures the user’s resting heart rate.
- walkingHeartRateAverage A quantity sample type that measures the user’s heart rate while walking.
- heartRateVariabilitySDNN A quantity sample type that measures the standard deviation of heartbeat intervals.
- heartRateRecoveryOneMinute A quantity sample that records the reduction in heart rate from the peak exercise rate to the rate one minute after exercising ended.
- atrialFibrillationBurden A quantity type that measures an estimate of the percentage of time a person’s heart shows signs of atrial fibrillation (AFib) while wearing Apple Watch.
- oxygenSaturation A quantity sample type that measures the user’s oxygen saturation.
- bodyTemperature A quantity sample type that measures the user’s body temperature.
- bloodPressureDiastolic A quantity sample type that measures the user’s diastolic blood pressure.
- bloodPressureSystolic A quantity sample type that measures the user’s systolic blood pressure.
- respiratoryRate A quantity sample type that measures the user’s respiratory rate.
Lab and test results
- bloodGlucose A quantity sample type that measures the user’s blood glucose level.
- electrodermalActivity A quantity sample type that measures electrodermal activity.
- forcedExpiratoryVolume1 A quantity sample type that measures the amount of air that can be forcibly exhaled from the lungs during the first second of a forced exhalation.
- forcedVitalCapacity A quantity sample type that measures the amount of air that can be forcibly exhaled from the lungs after taking the deepest breath possible.
- inhalerUsage A quantity sample type that measures the number of puffs the user takes from their inhaler.
- insulinDelivery A quantity sample that measures the amount of insulin delivered.
- numberOfTimesFallen A quantity sample type that measures the number of times the user fell.
- peakExpiratoryFlowRate A quantity sample type that measures the user’s maximum flow rate generated during a forceful exhalation.
- peripheralPerfusionIndex A quantity sample type that measures the user’s peripheral perfusion index.
Mindfulness and Sleep
- appleSleepingWristTemperature A quantity sample type that records the wrist temperature during sleep.
Nutrition
- dietaryBiotin A quantity sample type that measures the amount of biotin (vitamin B7) consumed.
- dietaryCaffeine A quantity sample type that measures the amount of caffeine consumed.
- dietaryCalcium A quantity sample type that measures the amount of calcium consumed.
- dietaryCarbohydrates A quantity sample type that measures the amount of carbohydrates consumed.
- dietaryChloride A quantity sample type that measures the amount of chloride consumed.
- dietaryCholesterol A quantity sample type that measures the amount of cholesterol consumed.
- dietaryChromium A quantity sample type that measures the amount of chromium consumed.
- dietaryCopper A quantity sample type that measures the amount of copper consumed.
- dietaryEnergyConsumed A quantity sample type that measures the amount of energy consumed.
- dietaryFatMonounsaturated A quantity sample type that measures the amount of monounsaturated fat consumed.
- dietaryFatPolyunsaturated A quantity sample type that measures the amount of polyunsaturated fat consumed.
- dietaryFatSaturated A quantity sample type that measures the amount of saturated fat consumed.
- dietaryFatTotal A quantity sample type that measures the total amount of fat consumed.
- dietaryFiber A quantity sample type that measures the amount of fiber consumed.
- dietaryFolate A quantity sample type that measures the amount of folate (folic acid) consumed.
- dietaryIodine A quantity sample type that measures the amount of iodine consumed.
- dietaryIron A quantity sample type that measures the amount of iron consumed.
- dietaryMagnesium A quantity sample type that measures the amount of magnesium consumed.
- dietaryManganese A quantity sample type that measures the amount of manganese consumed.
- dietaryMolybdenum A quantity sample type that measures the amount of molybdenum consumed.
- dietaryNiacin A quantity sample type that measures the amount of niacin (vitamin B3) consumed.
- dietaryPantothenicAcid A quantity sample type that measures the amount of pantothenic acid (vitamin B5) consumed.
- dietaryPhosphorus A quantity sample type that measures the amount of phosphorus consumed.
- dietaryPotassium A quantity sample type that measures the amount of potassium consumed.
- dietaryProtein A quantity sample type that measures the amount of protein consumed.
- dietaryRiboflavin A quantity sample type that measures the amount of riboflavin (vitamin B2) consumed.
- dietarySelenium A quantity sample type that measures the amount of selenium consumed.
- dietarySodium A quantity sample type that measures the amount of sodium consumed.
- dietarySugar A quantity sample type that measures the amount of sugar consumed.
- dietaryThiamin A quantity sample type that measures the amount of thiamin (vitamin B1) consumed.
- dietaryVitaminA A quantity sample type that measures the amount of vitamin A consumed.
- dietaryVitaminB12 A quantity sample type that measures the amount of cyanocobalamin (vitamin B12) consumed.
- dietaryVitaminB6 A quantity sample type that measures the amount of pyridoxine (vitamin B6) consumed.
- dietaryVitaminC A quantity sample type that measures the amount of vitamin C consumed.
- dietaryVitaminD A quantity sample type that measures the amount of vitamin D consumed.
- dietaryVitaminE A quantity sample type that measures the amount of vitamin E consumed.
- dietaryVitaminK A quantity sample type that measures the amount of vitamin K consumed.
- dietaryWater A quantity sample type that measures the amount of water consumed.
- dietaryZinc A quantity sample type that measures the amount of zinc consumed.
Alcohol consumption
- bloodAlcoholContent A quantity sample type that measures the user’s blood alcohol content.
- numberOfAlcoholicBeverages A quantity sample type that measures the number of standard alcoholic drinks that the user has consumed.
Mobility
- appleWalkingSteadiness A quantity sample type that measures the steadiness of the user’s gait.
- sixMinuteWalkTestDistance A quantity sample type that stores the distance a user can walk during a six-minute walk test.
- walkingSpeed A quantity sample type that measures the user’s average speed when walking steadily over flat ground.
- walkingStepLength A quantity sample type that measures the average length of the user’s step when walking steadily over flat ground.
- walkingAsymmetryPercentage A quantity sample type that measures the percentage of steps in which one foot moves at a different speed than the other when walking on flat ground.
- walkingDoubleSupportPercentage A quantity sample type that measures the percentage of time when both of the user’s feet touch the ground while walking steadily over flat ground.
- stairAscentSpeed A quantity sample type measuring the user’s speed while climbing a flight of stairs.
- stairDescentSpeed A quantity sample type measuring the user’s speed while descending a flight of stairs.
UV exposure
- timeInDaylight A quantity sample type that measures amount of time the user spent in daylight.
- uvExposure A quantity sample type that measures the user’s exposure to UV radiation.
Diving
- underwaterDepth A quantity sample that records a person’s depth underwater.
- waterTemperature A quantity sample that records the water temperature.
Initializers
- init(rawValue:)) Returns a newly initialized quantity type identifier using the provided string.
Type Properties
Creating quantity types
- quantityType(forIdentifier:)) Returns the shared quantity type for the provided identifier.
---
Extracted from Apple DocC JSON by apple-skills tooling. This is unofficial content. All documentation belongs to Apple Inc.
Navigation: HealthKit
Class
HKSampleQuery
Available on: iOS, iPadOS, Mac Catalyst, macOS, visionOS, watchOS
A general query that returns a snapshot of all the matching samples currently saved in the HealthKit store.
class HKSampleQueryOverview
You can use sample queries to search for any concrete subclasses of the HKSample class, including HKCategorySample, HKCorrelation, HKQuantitySample, and HKWorkout objects.
The sample query returns sample objects that match the provided type and predicate. You can provide a sort order for the returned samples, or limit the number of samples returned. Other query classes can be used to perform more specialized searches and calculations. For more information, see HKQuery.
Sample queries are immutable: The query’s properties are set when the query is first created, and they can’t change.
Note: Like many HealthKit classes, the HKSampleQuery class should not be subclassed.
Inherits From
Conforms To
- CVarArg
- CustomDebugStringConvertible
- CustomStringConvertible
- Equatable
- Hashable
- NSObjectProtocol
- Sendable
- SendableMetatype
Creating Sample Queries
- Executing Sample Queries Create, run, and sort sample queries.
- init(sampleType:predicate:limit:sortDescriptors:resultsHandler:)) Instantiates and returns a sample query.
- init(queryDescriptors:limit:resultsHandler:)) Creates a query for samples that match any of the descriptors you provided.
- init(queryDescriptors:limit:sortDescriptors:resultsHandler:)) Creates a query for samples that match any of the query descriptors you provided, sorted by the sort descriptors you provided.
- HKObjectQueryNoLimit A value indicating that the query returns all the matching samples in the HealthKit store.
- HealthKit sort descriptors Identifiers for sorting results.
Getting Property Data
- limit The maximum number of samples that this query returns.
- sortDescriptors The sort descriptors that specify the order of the results returned by this query.
Setting Limits
- HKObjectQueryNoLimit A value indicating that the query returns all the matching samples in the HealthKit store.
Basic queries
- HKSampleQueryDescriptor A query interface that reads samples using Swift concurrency.
- HKCorrelationQuery A query that performs complex searches based on the correlation’s contents, and returns a snapshot of all matching samples.
- HKQueryDescriptor A descriptor that specifies a set of samples based on the data type and a predicate.
- HKQuery An abstract class for all the query classes in HealthKit.
---
Extracted from Apple DocC JSON by apple-skills tooling. This is unofficial content. All documentation belongs to Apple Inc.
Navigation: HealthKit
Class
HKUnit
Available on: iOS 8.0+, iPadOS 8.0+, Mac Catalyst 13.0+, macOS 13.0+, visionOS 1.0+, watchOS 2.0+
A class for managing the units of measure within HealthKit.
class HKUnitOverview
The unit class supports most standard SI units (meters, seconds, and grams), SI units with prefixes (centimeters, milliseconds and kilograms) and equivalent non-SI units (feet, minutes, and pounds). HealthKit also supports creating complex units by mathematically combining existing units.
You use units when working with HealthKit quantities. Quantities store both the value (as a double data type) and its corresponding unit. You can then request the value from the quantity in any compatible units. For more information on working with quantities, see HKQuantity.
Note: Number formatters that use units (for example, EnergyFormatter, LengthFormatter, and MassFormatter) use a custom enumeration to specify their units. For example, the EnergyFormatter class uses the EnergyFormatter.Unit enum. The HKUnit class provides several methods to translate between the formatter enumerations and the HealthKit units. For more information, see Working with formatter units.
Using Units
Like many HealthKit classes, the HKUnit class is not extendable and should not be subclassed.
The HKUnit class is implemented using a facade design pattern. It uses custom subclasses to represent instances of the different unit types. For example, the second()) convenience method actually returns an instance of the private HKTimeUnit subclass.
Additionally, the unit class uses a single unit instance to represent all copies of the same unit in your app, wherever possible. For example, two calls to the second()) method return the same unit object. This helps reduce the amount of memory used by unit instances.
Inherits From
Conforms To
- CVarArg
- CustomDebugStringConvertible
- CustomStringConvertible
- Equatable
- Hashable
- NSCoding
- NSCopying
- NSObjectProtocol
- NSSecureCoding
- Sendable
- SendableMetatype
Working with units
- init(from:)-9qont) Returns the unit instance described by the provided string.
- unitString A string representation of the unit object.
- isNull()) Returns a Boolean value indicating whether the unit is null.
Working with formatter units
- energyFormatterUnit(from:)) Converts a HealthKit unit object into a corresponding energy formatter enumeration value.
- init(from:)-1j1pq) Converts an energy formatter enumeration value into a corresponding HealthKit unit object.
- lengthFormatterUnit(from:)) Converts a HealthKit unit object into a corresponding length formatter enumeration value.
- init(from:)-55e1u) Converts a length formatter enumeration value into a corresponding HealthKit object.
- massFormatterUnit(from:)) Converts a HealthKit unit object into a corresponding mass formatter enumeration value.
- init(from:)-7h2li) Converts a mass formatter enumeration value into a corresponding HealthKit unit object.
Constructing mass units
- gram()) Returns a HealthKit unit for measuring mass in grams.
- gramUnit(with:)) Returns a HealthKit unit for measuring mass, using gram units with the provided prefix.
- ounce()) Returns a HealthKit unit for measuring mass in ounces.
- pound()) Returns a HealthKit unit for measuring mass in pounds.
- stone()) Returns a HealthKit unit for measuring mass in stones.
- moleUnit(withMolarMass:)) Returns a HealthKit unit for measuring mass in moles for a given molar mass.
- moleUnit(with:molarMass:)) Returns a HealthKit unit for measuring mass in moles, with the given prefix and molar mass.
- HKUnitMolarMassBloodGlucose The molecular mass of blood glucose, typically used to create mole units for blood glucose.
Constructing length units
- meter()) Returns a HealthKit unit for measuring length in meters.
- meterUnit(with:)) Returns a HealthKit unit for measuring length, using meter units with the provided prefix.
- inch()) Returns a HealthKit unit for measuring length in inches.
- foot()) Returns a HealthKit unit for measuring length in feet.
- yard()) Returns a HealthKit unit for measuring length in yards.
- mile()) Returns a HealthKit unit for measuring length in miles.
Constructing volume units
- liter()) Returns a HealthKit unit for measuring volume in liters.
- literUnit(with:)) Returns a HealthKit unit for measuring volume, using liter units with the provided prefix.
- fluidOunceUS()) Returns a HealthKit unit for measuring volume in US fluid ounces.
- fluidOunceImperial()) Returns a HealthKit unit for measuring volume in imperial fluid ounces.
- cupUS()) Returns a HealthKit unit for measuring volume in US cups.
- cupImperial()) Returns a HealthKit unit for measuring volume in imperial cups.
- pintUS()) Returns a HealthKit unit for measuring volume in US pints.
- pintImperial()) Returns a HealthKit unit for measuring volume in imperial pints.
Constructing pressure units
- pascal()) Returns a HealthKit unit for measuring pressure in pascals.
- pascalUnit(with:)) Returns a HealthKit unit for measuring pressure, using pascal units with the provided prefix.
- millimeterOfMercury()) Returns a HealthKit unit for measuring pressure in millimeters of mercury.
- inchesOfMercury()) Returns a HealthKit unit for measuring pressure in inches of mercury.
- centimeterOfWater()) Returns a HealthKit unit for measuring pressure in centimeters of water.
- atmosphere()) Returns a HealthKit unit for measuring pressure in atmospheres.
- decibelAWeightedSoundPressureLevel()) Returns a HealthKit unit for measuring the difference between the local pressure and the ambient atmospheric pressure caused by sound.
Constructing time units
- second()) Returns a HealthKit unit for measuring time in seconds.
- secondUnit(with:)) Returns a HealthKit unit for measuring time, using second units with the provided prefix.
- minute()) Returns a HealthKit unit for measuring time in minutes.
- hour()) Returns a HealthKit unit for measuring time in hours.
- day()) Returns a HealthKit unit for measuring time in days.
Constructing energy units
- joule()) Returns a HealthKit unit for measuring energy in joules.
- jouleUnit(with:)) Returns a HealthKit unit for measuring energy, using joule units with the provided prefix.
- kilocalorie()) Returns a HealthKit unit for measuring energy in kilocalories.
- largeCalorie()) Returns a HealthKit unit for measuring energy in large calories (Cal).
- smallCalorie()) Returns a HealthKit unit for measuring energy in small calories (cal).
- calorie()) Returns a HealthKit unit for measuring energy in calories.
Constructing power units
- watt()) Returns a HealthKit unit for measuring power in watts.
- wattUnit(with:)) Returns a HealthKit unit for measuring power, using watt units with the provided prefix.
Constructing temperature units
- degreeCelsius()) Returns a HealthKit unit for measuring temperature in degrees Celsius.
- degreeFahrenheit()) Returns a HealthKit unit for measuring temperature in degrees Fahrenheit.
- kelvin()) Returns a HealthKit unit for measuring temperature in kelvins.
Constructing hearing sensitivity units
- decibelHearingLevel()) Returns a HealthKit unit for measuring the intensity of a sound.
Constructing frequency units
- hertz()) Returns a HealthKit unit for measuring frequency in hertz.
- hertzUnit(with:)) Returns a HealthKit unit for measuring frequency in hertz with the provided prefix.
Constructing vision units
- diopter()) Returns a HealthKit unit for measuring the optical power of a lens using diopter units.
- prismDiopter()) Returns a HealthKit unit for measuring the prismatic deviation of a lens using prism diopter units.
Constructing angle units
- degreeAngle()) Returns a HealthKit unit for measuring angles using degrees.
- radianAngle()) Returns a HealthKit unit for measuring angles using radians.
- radianAngleUnit(with:)) Returns a HealthKit unit for measuring angles, using radian units with the provided prefix.
Constructing electrical conductance units
- siemen()) Returns a HealthKit unit for measuring electrical conductance in siemens.
- siemenUnit(with:)) Returns a HealthKit unit for measuring electrical conductance, using siemen units with the provided prefix.
Electrical potential difference
- volt()) Returns a HealthKit unit for measuring the difference in electrical potential using volts.
- voltUnit(with:)) Returns a HealthKit unit for measuring the electrical potential difference in volts with the provided prefix.
Constructing pharmacology units
- internationalUnit()) Returns a HealthKit unit that measures the amount of a biologically active substance in international units (IU).
Constructing scalar units
- count()) Returns a HealthKit unit for measuring counts.
- percent()) Returns a HealthKit unit for measuring percentages.
Performing unit math
- unitMultiplied(by:)) Creates a complex unit by multiplying the receiving unit with another unit.
- unitDivided(by:)) Creates a complex unit by dividing the receiving unit by another unit.
- unitRaised(toPower:)) Creates a complex unit by raising the unit to the given power.
- reciprocal()) Returns a complex unit representing the unit’s reciprocal.
Constants
- HKMetricPrefix Prefixes that can be added to SI units to change the order of magnitude.
Initializers
- init(coder:))
- init(fromEnergyFormatterUnit:))
- init(fromLengthFormatterUnit:))
- init(fromMassFormatterUnit:))
- init(fromString:))
Type Methods
- appleEffortScore())
- lux()) Returns a HealthKit unit for measuring illuminance in lux.
- luxUnit(with:)) Returns a HealthKit unit for measuring illuminance, using lux units with the provided prefix.
Units and quantities
- Defining and converting units and quantities Create and convert units and quantities.
- HKQuantity An object that stores a value for a given unit.
- HKMetricPrefix Prefixes that can be added to SI units to change the order of magnitude.
---
Extracted from Apple DocC JSON by apple-skills tooling. This is unofficial content. All documentation belongs to Apple Inc.
Related skills
How it compares
Use healthkit for native Apple HealthKit on iOS and watchOS; pick a cross-platform health SDK skill when the same code must also target Android Health Connect.
FAQ
Which platforms does the healthkit skill cover?
The healthkit skill covers iOS and watchOS HealthKit integration, including permission prompts, read and write sample types, background delivery, and syncing workouts or vitals across companion targets.
What HealthKit features does the skill address?
The healthkit skill addresses authorization requests, background delivery configuration, workout session handling, and vitals synchronization using native Apple HealthKit APIs and required entitlements.