I’m trying to associate heart rate (HR) data with a mindfulness session (HKCategoryTypeIdentifier.mindfulSession) in HealthKit, but I can’t find any documentation on how to do this.
I’ve seen third-party apps (like Medito) successfully log HR within Mindful Minutes, even when the session takes place on an iPhone (not an Apple Watch). However, when I try saving HR in the metadata, it does not appear in the Health app's Mindful Minutes section.
Code snippet:
func logMindfulnessSession(start: Bool, heartRate: Double? = nil) {
let mindfulType = HKCategoryType.categoryType(forIdentifier: .mindfulSession)!
let now = Date()
let endTime = now.addingTimeInterval(Double(selectedDuration))
var metadata: [String: Any]? = nil
if let hr = heartRate {
let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute())
let hrQuantity = HKQuantity(unit: heartRateUnit, doubleValue: hr)
metadata = ["heartRate": hrQuantity] // ❓ Is there a correct key for HR?
}
let sample = HKCategorySample(
type: mindfulType,
value: 0,
start: now,
end: endTime,
metadata: metadata
)
healthStore.save(sample) { success, error in
if let error = error {
print("HealthKit session save error: \(error.localizedDescription)")
} else {
print("Mindfulness session saved successfully.")
if let hr = heartRate {
print("Saved with HR: \(hr) BPM")
}
}
}
}
Questions:
- What is the correct metadata key for associating heart rate with a mindful session?
- Does HealthKit require a specific format (e.g., HKQuantitySample) for HR?
0 Are there additional permissions needed to allow HR to appear in Mindful Minutes?
- Does HR need to be stored separately in HKQuantityTypeIdentifier.heartRate, and if so, how do third-party apps ensure it appears in the same entry as the mindful session?
thank you!
I don't think we expose any metadata key that can tie a heart rate to a mindful session as of today, but if you create a heart rate sample that is aligned to the time of the mindful session, as shown in the following code, the heart rate will show up in the Finess.app:
let endTime = Date()
let startTime = endTime.addingTimeInterval(-60 * 1)
let mindfulSessionSample = HKCategorySample(
type: HKCategoryType(.mindfulSession),
value: 0, start: startTime, end: endTime, metadata: nil
)
let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute())
let hrQuantity = HKQuantity(unit: heartRateUnit, doubleValue: 56)
let heartRateSample = HKQuantitySample(
type: HKQuantityType(.heartRate),
quantity: hrQuantity, start: startTime, end: startTime
)
healthStore.save([mindfulSessionSample, heartRateSample]) { success, error in
if let error = error {
print("HealthKit session save error: \(error.localizedDescription)")
} else {
print("Mindfulness session saved successfully.")
}
}
Note that you need to have the user authorization to write / share the following HealthKit data types:
HKQuantityType(.heartRate),
HKCategoryType(.mindfulSession)
Best,
——
Ziqiao Chen
Worldwide Developer Relations.