Access Health data in your Spezi app.
The Spezi HealthKit module enables apps to integrate with Apple's HealthKit system, fetch data, set up long-lived background data collection, and visualize Health-related data.
You need to add the Spezi HealthKit Swift package to your app in Xcode or Swift package.
Important: If your application is not yet configured to use Spezi, follow the Spezi setup article and set up the core Spezi infrastructure.
Before you configure the HealthKit-class
module, make sure your Standard
in your Spezi Application conforms to the HealthKitConstraint
protocol to receive HealthKit data. The HealthKitConstraint/add(sample:)
function is triggered once for every newly collected HealthKit sample, and the HealthKitConstraint/remove(sample:)
function is triggered once for every deleted HealthKit sample.
actor ExampleStandard: Standard, HealthKitConstraint {
// Add the newly collected HKSample to your application.
func add(sample: HKSample) async {
// ...
}
// Remove the deleted HKSample from your application.
func remove(sample: HKDeletedObject) {
// ...
}
}
Then, you can configure the HealthKit-class
module in the configuration section of your SpeziAppDelegate
.
Provide HealthKitDataSourceDescription
to define the data collection.
You can, e.g., use CollectSample
to collect a wide variety of HKSampleTypes
:
class ExampleAppDelegate: SpeziAppDelegate {
override var configuration: Configuration {
Configuration(standard: ExampleStandard()) {
HealthKit {
CollectSample(.activeEnergyBurned)
CollectSample(.stepCount, start: .manual)
CollectSample(.pushCount, start: .manual)
CollectSample(.heartRate, continueInBackground: true)
CollectSample(.electrocardiogram, start: .manual)
RequestReadAccess(quantity: [.bloodOxygen])
}
}
}
}
You can use SpeziHealthKitUI
's HealthKitQuery
and HealthKitStatisticsQuery
property wrappers to access the Health database in a View:
struct ExampleView: View {
@HealthKitQuery(.heartRate, timeRange: .today)
private var heartRateSamples
var body: some View {
ForEach(heartRateSamples) { sample in
// ...
}
}
}
Additionally, you can use SpeziHealthKitUI
's HealthChart
to visualise query results:
struct ExampleView: View {
@HealthKitQuery(.heartRate, timeRange: .today)
private var heartRateSamples
var body: some View {
HealthChart {
HealthChartEntry($heartRateSamples, drawingConfig: .init(mode: .line, color: .red))
}
}
}
For more information, please refer to the API documentation.
The Spezi Template Application provides a great starting point and example using the SpeziHealthKit
module.
Contributions to this project are welcome. Please make sure to read the contribution guidelines and the contributor covenant code of conduct first.
This project is licensed under the MIT License. See Licenses for more information.