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!
Use HealthKit to enable your iOS and watchOS apps to work with the Apple Health app.
Post
Replies
Boosts
Views
Activity
Platform & Version:
iOS Version: 18.3.1
Development Environment: Xcode 16.2, macOS 14.6.1
Description of the Issue:
We're exploring ways to better integrate Apple Fitness+ workouts into our app. We've noticed that some third-party apps, such as Strava and HealthFit, now display Fitness+ workout details, including the title, trainer, and an image.
I’ve been investigating how this is possible, and the only relevant change I’ve found is that HKMetadataKeyAppleFitnessPlusCatalogIdentifier is now being set for Fitness+ workouts. However, I can’t find any public API or official documentation that explains how to use these identifiers to retrieve the associated workout details.
Question:
Is there an official API available to fetch metadata for Fitness+ workouts using these identifiers? Or are these third-party apps potentially accessing private APIs? If no API exists, is the only option to create a manual mapping of these identifiers—something that seems impractical given the constantly evolving Fitness+ workout catalog?
Any guidance on this would be greatly appreciated. Thanks!
The background deliver works perfectly when the app is in the background or suspended states. However, when the app is killed (terminated state), the background task does not execute
Is it possible to develop the following app? The app will measure heart rate variability five times at 2-minute intervals triggered by an event and output the values.
Hello,
I am building a workout app that has an option to add segments to differentiate different stages of the training session. Segments are added the following way:
func saveSegment(eventType: HKWorkoutEventType, startDate: Date, endDate: Date, inSeg: Int) async throws {
let dateInterval = DateInterval(start: startDate, end: endDate)
let event = HKWorkoutEvent(type: eventType, dateInterval: dateInterval, metadata: metadata)
try await builder?.addWorkoutEvents([event])
}
Inside Health -> Workouts -> Show All Data, the segments appear, but in Fitness app there are no segments. The workout is .paddleSports. I thought that maybe the workout type was the problem, but when I start the sessions from the native workout app, segments are added and shown in the Fitness app:
In other posts I saw suggested to add an event as .marker instead of .segment, but the result is the same, it does not appear.
Is there something I am doing wrong? How can I show the segments into the Fitness app?
Another question, I would like to add stroke rate and stroke count to my paddling session, is there a way to add it? Paddle Sports workout was recently introduced and it would be great to have the option to add those values.
Thank you in advance.
Inaki
In the fitness app under iOS 18, the location of all workouts is displayed on a small map.
For workouts with routes, I can already successfully read out the route and thus also determine the starting point. So that works.
For indoor workouts such as yoga or indoor rowing, the exact location is also displayed in the fitness app. I would now also like to read out this location for these indoor workouts in my app.
Does anyone know how to do this?
I am working on an Apple Watch companion app to an existing live iOS app. I am utilizing the heart rate tracking for an active 'self-care' sauna session. I say self-care in quotes because it's more self-care than a workout activity, but it is closely blurring the lines between the two.
I have come to understand that if a session truly isn't a workout, then you should not use workoutSession.startActivity. However the app needs to function entirely like a workout would. This is not a meditation application. Sauna is actually just one of many activity types supported in the app.
I have tried using extended runtime session, and there have been numerous issues with doing so. It is not nearly as robust for the user. For example, the active session is not prioritized by the watch's CPU. Now playing is no longer functional. Heart rate is far more inconsistent, and this variable is as critical as if it were in a workout.
I have tried using HKWorkoutSession, however I worry the app will be rejected by doing so. This method works most accurately to collect the right data for the user, and prioritizes system resources as expected. The app can be moved to the background as expected and continue to communicate with the iOS app.
What is the best way to move forward here. It almost feels like I am operating in a grey area with no real solution in place. Any assistance is greatly appreciated as we would like to follow all guidelines while producing a high quality experience for our users.
Hello,
My app syncs workout data from a third-party device and records workouts with HealthKit as follows:
let builder = HKWorkoutBuilder(healthStore: healthStore, configuration: hkConf, device: hkDevice)
try await builder.beginCollection(at: startDate)
try await builder.addSamples(samples)
try await builder.endCollection(at: endDate)
let workout = try await builder.finishWorkout()
let workoutRouteBuilder = HKWorkoutRouteBuilder(healthStore: healthStore, device: hkDevice)
try await workoutRouteBuilder.insertRouteData(filteredLocations)
try await workoutRouteBuilder.finishRoute(with: workout, metadata: nil)
However, I’m encountering two issues:
The workouts appear in Apple Fitness but do not contribute to the activity rings.
The workout includes a route (visible in the raw workout data in Apple Health) but does not display on Apple Fitness.
Is there any way to fix this? I’d appreciate any suggestions you might have.
__
In my WatchOS app I've written the following code to check if my app has access to the user's health data:
func isHealthKitAuthorized() -> Bool {
let typesToRead: [HKObjectType] = [
HKObjectType.quantityType(forIdentifier: .heartRate)!,
HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,
HKObjectType.quantityType(forIdentifier: .appleMoveTime)!,
HKObjectType.quantityType(forIdentifier: .appleExerciseTime)!,
HKObjectType.workoutType()
]
let typesToShare: Set<HKSampleType> = [
HKObjectType.workoutType(),
HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,
HKObjectType.quantityType(forIdentifier: .heartRate)!
]
var isAuthorized = true
for type in typesToRead {
let status = healthStore.authorizationStatus(for: type)
if status != .sharingAuthorized {
print("Access denied to: \(type.identifier)")
isAuthorized = false
}
}
for type in typesToShare {
let status = healthStore.authorizationStatus(for: type)
if status != .sharingAuthorized {
print("Access denied to: \(type.identifier)")
isAuthorized = false
}
}
return isAuthorized
}
However for the appleMoveTime and appleExerciseTime types their status is returning as 'sharingDenied' (checked by printing the status' rawValue) even though they are authorized on the Watch's settings. This happened both on the simulator and on the Watch itself. Am I doing something wrong?
Is there documentation on how to read workout effort scores from a HealthKit workout? I'm interested in reading workoutEffortScore and estimatedWorkoutEffortScore. I have not been successful trying to read them using the same method that I do other workout HKQuantityTypes (heartRate, stepCount, etc). I'm using Swift and I do have authorization for those types requested and granted.
I have found documentation on setting these values (https://developer.apple.com/forums/thread/763539) but not reading them.
Thank You
I'm dealing with a strange bug where I am requesting read access for 'appleExerciseTime' and 'activitySummaryType', and despite enabling both in the permission sheet, they are being set to 'sharingDenied'.
I'm writing a Swift Test for making sure permissions are being granted.
@Test
func PermissionsGranted() {
try await self.manager.getPermissions()
for type in await manager.allHealthTypes {
let status = await manager.healthStore.authorizationStatus(for: type)
#expect(status == .sharingAuthorized, "\(type) authorization status is \(status)")
}
}
let healthTypesToShare: Set<HKSampleType> = [
HKQuantityType(.bodyMass),
HKQuantityType(.bodyFatPercentage),
HKQuantityType(.leanBodyMass),
HKQuantityType(.activeEnergyBurned),
HKQuantityType(.basalEnergyBurned),
HKObjectType.workoutType()
]
let allHealthTypes: Set<HKObjectType> = [
HKQuantityType(.bodyMass),
HKQuantityType(.bodyFatPercentage),
HKQuantityType(.leanBodyMass),
HKQuantityType(.activeEnergyBurned),
HKQuantityType(.basalEnergyBurned),
HKQuantityType(.appleExerciseTime),
HKObjectType.activitySummaryType()
]
let healthStore = HKHealthStore()
func getPermissions() async throws {
try await healthStore.requestAuthorization(toShare: self.healthTypesToShare, read: self.allHealthTypes)
}
After 'getPermissions' runs, the permission sheet shows up on the Simulator, and I accept all. I've double checked that the failing permissions show up on the sheet and are enabled. Then the test fails with:
Expectation failed: (status → HKAuthorizationStatus(rawValue: 1)) == (.sharingAuthorized → HKAuthorizationStatus(rawValue: 2)) HKActivitySummaryTypeIdentifier authorization status is HKAuthorizationStatus(rawValue: 1)
Expectation failed: (status → HKAuthorizationStatus(rawValue: 1)) == (.sharingAuthorized → HKAuthorizationStatus(rawValue: 2)) HKActivitySummaryTypeIdentifier authorization status is HKAuthorizationStatus(rawValue: 1)
With the rawValue of '1' being 'sharingDenied'. All other permissions are granted. Is there a workaround here, or something I'm potentially doing wrong?
Good afternoon,
I am working on a workout tracking app. So far everything is working as expected. However, I note that when my workout saves and is visible within the Fitness App, the workout duration is displayed rather than the kCal burned.
What changes are required to be made in order for this to display the kCal in the list of workouts in Fitness rather than duration?
For reference https://developer.apple.com/videos/play/wwdc2021/10009 this was my reference source for workout functionality.
I have a workout app which I am testing on device currently via TestFlight.
The generated workout (tennis and indoor) shows in the fitness app with correct HR and duration.
However, when I go to my Strava app, it does not show in the list of workouts for importing. (note, activities tracked using the regular tennis mode on the Apple Watch show fine)
I have also concurrently reached out to Strava support to see if there's anything they can offer support for.
However, does anybody here have any knowledge/experience of the requirement? Or whether this is a limitation of an application deployed via TestFlight?
I have a terrible feeling I am chasing ghosts, and it may be a TestFlight limitation for exporting workouts?
Thanks
I am writing to address a concern regarding the background permission functionality in my app, which is critical for ensuring user safety as they navigate various terrains. This feature also enables users to smoothly record their navigation tracks for review after their activities. Recently, I've noticed that this functionality is not working as seamlessly as before.
Additionally, I observed that the app is not categorized under 'health and fitness'—could reclassifying it improve background activity? Before I delve into a detailed code review, I wanted to check if this issue might be related to sync or settings on the App Store side, such as permission configurations, app updates, or other related factors. Or, is it more likely an issue stemming from the app’s codebase?
We have working code to fetch step data from HealthKit after requesting the necessary permissions. However, we’ve encountered an issue specific to one device, the iPhone 16 Pro Max. When querying the data, we do not receive a response, and the code enters an infinite loading state without completing the request.
The user who is facing this issue has tried logging in on another device, and it works fine. On the problematic device (iPhone 16 Pro Max), the request does not complete.
For reference, I’ve included the code below. Resolving this issue is crucial, so we would appreciate any guidance on what steps we can take to troubleshoot or resolve the problem on this specific device.
Please note that the device has granted permission to access HealthKit data.
static let healthStore = HKHealthStore()
static func limitReadFromHealthKitBetweenDates(fromDate: Date, toDate: Date = Date(), completion: @escaping ([HKStatistics]) -> Void) {
guard let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount) else { return }
let ignoreUserEntered = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyWasUserEntered, operatorType: .notEqualTo, value: true)
let now = toDate
var interval = DateComponents()
interval.day = 1
var calendar = Calendar.current
calendar.locale = Locale(identifier: "en_US_POSIX")
var anchorComponents = calendar.dateComponents([.day, .month, .year], from: now)
anchorComponents.hour = 0
let anchorDate = calendar.date(from: anchorComponents) ?? Date()
let query = HKStatisticsCollectionQuery(quantityType: stepsQuantityType,
quantitySamplePredicate: ignoreUserEntered,
options: [.cumulativeSum],
anchorDate: anchorDate,
intervalComponents: interval)
query.initialResultsHandler = { _, results, error in
guard let results = results else {
print("Error returned from resultHandler: \(String(describing: error?.localizedDescription))")
return
}
print(results)
var statisticsArray: [HKStatistics] = []
results.enumerateStatistics(from: fromDate, to: now) { statistics, _ in
statisticsArray.append(statistics)
if statistics.endDate.getddmmyyyyslashGMT == now.getddmmyyyyslashGMT {
completion(statisticsArray)
}
}
}
healthStore.execute(query)
}
Please note that the code works on all devices except the problematic one. Could you please guide me on the next steps to resolve this issue?
Hi everyone,
I’m developing a health-related mobile app and considering using EAS Update to deliver over-the-air (OTA) updates for JavaScript code and assets. Before implementing this, I want to ensure that this approach complies with Apple App Store policies, especially given the sensitivity of health-related apps.
Here are my concerns:
Does using EAS Update (OTA) align with Apple’s guidelines regarding app updates and dynamic behavior changes?
Are there specific rules or restrictions for health apps using OTA updates that I should be cautious of?
Could this approach be flagged as violating Apple’s policies on app integrity, especially those requiring updates to go through the App Store review process?
I’d greatly appreciate any insights, advice, or references to Apple’s official documentation regarding OTA updates for apps distributed through the App Store.
Thanks in advance for your help!
We currently use the HKCategoryValueMenstrualFlow enum to determine the type of menstrual flow: light, medium, etc. a user is having. We also use this enum in determining if it's an actual period day.
The Problem
I see HKCategoryValueMenstrualFlow was recently deprecated but has not been replaced by another data type.
Are there plans to replace/update it with another data type?
When or at what point in the future will this deprecation cause a problem in my code?
As a user, there are times when I don't wear my sleep tracker to bed, but I nonetheless want to record my sleep times.
Apple Health supports this with the "Add Data" feature, but it's not possible to provide a time zone in the form.
Then as a developer, user-added sleep samples are missing time zone information.
I would expect that the time zone is requested within the Add Data form.
Without this information provided at input time, downstream applications are forced to infer the time zone ourselves, leading to potentially buggy or unintuitive behavior.
Finally at last Apple Health supports saving .distancePaddleSports, .distanceCrossCountrySkiing, .distanceRowing, .distanceSkatingSports, and much more.
The backstory. In the land of 10,000 lakes, there hasn't been a way to save 'canoe' or 'kayak' distance and I've been asking for it for years. Thank you health team for adding it this year!
FB7807993 - Add HKQuantityTypeIdentifier.paddleDistance for canoeing, kayaking, etc type workouts (June 2020)
Prior we could just save the totalDistance to a workout, but since the HKWorkout initializers were deprecated we no longer have a supported way to save these distances in our workouts. The iOS 18 / watchOS 11 introduction addresses this. If you want to know more why you can't do this in earlier versions you can check these feedback titles:
FB10281482 - HealthKit: Deprecation of totalDistance on a workout session of paddleSports breaks apps that used that to save distance to the workout because there is no "paddleDistance" type available to save as sample data (June 2022)
FB12402974 - HealthKit: Deprecation of HKWorkout completely breaks support for third party fitness apps from saving non-standard workout distance (June 2023)
Great, so there is new support that solves all of these requests and issues for the new version of the OSes. However, the downside is now that there is not much for documentation. Unlike the .runningSpeed and .runningPower introduced in iOS 16 / watchOS 9, none of the new iOS 18 / watchOS 11 types have documentation, at all. To some degree this is understandable, but types from last year still remain undocumented too.
Without this information for the data types introduced in both iOS 17/18 and watchOS 10/11 it makes building and integrating with these new types difficult to say the least. We can't make assumptions about anything.
Can we get a documentation update for new (and existing) quantity types for when Apple Watch will automatically generate samples?
FB14236080 - Developer Documentation / HealthKit: Update documentation for HKLiveWorkoutDataSource typesToCollect for which sample types are automatically collected by watchOS 10 and 11 (July 2024)
FB14942555 - HealthKit / Documentation: App Update Release Issue - HKQuantityTypeIdentifiers are missing documentation describing when the system automatically adds data (today)
I know that the behavior has changed from release to release for some of these types, so documentation would be based on OS version. If you didn't catch it, watchOS 11 will now associate .cyclingSpeed for cycling workouts both indoor and outdoor.
FB12458548 - Fitness: Connected cycling speed sensor did not save samples to health via cycling workout (June 2023 - received reply that only saved for indoor cycling, but not documented otherwise)
FB14311218 - HealthKit: Expected outdoor cycling to include .cyclingSpeed quantity type as a default HKLiveWorkoutDataSource type to collect (July 2024)
To the other third party fitness apps out there, how are you managing the knowledge of which devices collect which data types on which versions of the OS?
Sure, we could look at the HKLiveWorkoutDatSource and inspect the typesToCollect property across a bunch of devices, but again that is trial by error not 'as documented'. Is the behavior of simulators guaranteed to match the behavior of real devices? Maybe, but also maybe not.
Fingers crossed for a nice documentation update to spell out all of the behavioral details.
Apple folks / DTS, many of the above feedbacks are addressed and I plan to update or close them after the releases this fall. Some are still outstanding.
P.S. I hope that .paddleSports gets deprecated and split into individual activity types like skiing did years ago. Their MET scores are different according to the research on the physical activity compendium site.
FB7807902 - Split HKWorkoutActivityType.paddleSports into their own activity types (June 2020)
Hi,
I am part of a team working to incorporate vehicle crash detection using SafetyKit. However, I am unable to know more details about this entitlement since the details page (https://developer.apple.com/contact/request/vehicular-crash-events/) is showing an unauthorised message as shown in the image below.
All the latest licenses have been reviewed and agreed to. Please let me know what can be done to access this link and know the details of this entitlement.