Use HealthKit to enable your iOS and watchOS apps to work with the Apple Health app.

All subtopics
Posts under Health and Fitness topic

Post

Replies

Boosts

Views

Activity

Support for cycling power & cadence sensors in HKWorkoutSession on iOS?
Hi everyone, while testing HKWorkoutSession with HKLiveWorkoutBuilder on iOS 26 Beta (cycling workout), I noticed the following behavior: – Starting a cycling HKWorkoutSession automatically connects to my Bluetooth heart rate monitor and records HR into HealthKit ✅ – However, my Bluetooth cycling power meter and cadence sensor (standard BLE Cycling Power & CSC services) are not connected automatically, and no data is recorded into HealthKit ❌ On Apple Watch, when starting a cycling workout, these sensors do connect automatically and their data is written to HealthKit — which is exactly what I would expect on iOS as well. Question: Is this by design, or is support for power and cadence sensors planned for iOS in the same way as on watchOS? Or do we, as developers, need to implement the BLE Cycling Power and CSC profiles ourselves (via CoreBluetooth) if we want these metrics? Environment: – iOS 26 Beta – HKWorkoutSession & HKLiveWorkoutBuilder (cycling) – Bluetooth HRM connects automatically – BLE power & cadence sensors do not This feature would make it much easier to develop cycling apps with full HealthKit integration, and also create a more consistent user experience compared to watchOS. Thanks for any insights!
1
0
37
4d
HKLiveWorkoutBuilder get wrong calorie data for iOS 26
In iOS 26, HKLiveWorkoutBuilder is supported, which we can use like HKWorkoutSession in watchOS - this is very exciting. However, it currently seems to have a bug in calculating calories. I tested it in my app, and for nearly 6 minutes with an average heart rate of 134, it only calculated 8 calories consumed (80 calories per hour), including basal consumption, which is obviously incorrect. (I used Powerboats Pro 2 connected to my phone, which includes heart rate data, and HKLiveWorkoutBuilder correctly collected the heart rate, which is great.) I think my code is correct. func workoutBuilder(_ workoutBuilder: HKLiveWorkoutBuilder, didCollectDataOf collectedTypes: Set<HKSampleType>) { for type in collectedTypes { guard let quantityType = type as? HKQuantityType else { return // Nothing to do. } let statistics = workoutBuilder.statistics(for: quantityType) if let statistics = statistics { switch statistics.quantityType { case HKQuantityType.quantityType(forIdentifier: .heartRate): /// - Tag: SetLabel let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute()) let value = statistics.mostRecentQuantity()?.doubleValue(for: heartRateUnit) let roundedValue = Double( round( 1 * value! ) / 1 ) if let avg = statistics.averageQuantity()?.doubleValue(for: heartRateUnit) { self.avgHeartRate = avg } self.delegate?.didUpdateHeartBeat(self, heartBeat: Int(roundedValue)) case HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned): let energyUnit = HKUnit.kilocalorie() let value = statistics.sumQuantity()?.doubleValue(for: energyUnit) self.totalActiveEnergyBurned = Double(value!) print("didUpdate totalActiveEnergyBurned: \(self.totalActiveEnergyBurned)") self.delegate?.didUpdateEnergyBurned(self, totalEnergy: self.totalActiveEnergyBurned + self.totalBasalEneryBurned) return case HKQuantityType.quantityType(forIdentifier: .basalEnergyBurned): let energyUnit = HKUnit.kilocalorie() let value = statistics.sumQuantity()?.doubleValue(for: energyUnit) self.totalBasalEneryBurned = Double(value!) print("didUpdate totalBasalEneryBurned: \(self.totalBasalEneryBurned)") self.delegate?.didUpdateEnergyBurned(self, totalEnergy: self.totalActiveEnergyBurned + self.totalBasalEneryBurned) return default: print("unhandled quantityType=\(statistics.quantityType) when processing statistics") return } } I think I've found the source of the problem: let workoutConfiguration = HKWorkoutConfiguration() workoutConfiguration.activityType = .traditionalStrengthTraining //walking, running is ok workoutConfiguration.locationType = .outdoor When I set the activityType to walking or running, the calorie results are correct, showing several hundred calories per hour. However, when activityType is set to traditionalStrengthTraining or jumprope, the calculations are incorrect. PS: I'm currently using Xcode 26 beta3 and iOS 26 beta3. Hope this issue can be resolved. Thanks.
1
0
58
1w
Some swimming activities are not fetched by combined predicate
I'm using following filters to fetch swimming activities from HealthKit. For some users it fetches all workouts (pool && open water) but for other it skips some open water activities. See screenshot, all those swimming activities are not fetched by following code. let startDate = Calendar.current.date(byAdding: .month, value: -1, to: Date())! let endDate = Date() let swimmingPredicate = HKQuery.predicateForWorkouts(with: .swimming) let timePredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate) let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [swimmingPredicate, timePredicate]) let query = HKSampleQuery(sampleType: .workoutType(), predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [.init(keyPath: \HKSample.startDate, ascending: false)], resultsHandler: { [weak self] query, samples, error in ... Could someone help with ideads what is missing in this case?
0
0
26
1w
Workout Buddy not available
Has anyone seen the workout buddy options on watch OS yet? I am not able to get it on my watch. My setup is an iPhone 16 and Watch Ultra 1 with the 26 OS I am currently using beta 3. English US language on both and US as region. I am located in Germany though. I restarted both devices multiple times without any changes. Hopefully someone can help.
1
0
32
1w
Adding workoutEffortScore to HKWorkout
I'm trying to hook into the new workoutEffort score supported in iOS 18, I am collecting this information from users when they submit their workout and trying to add a sample to the HKWorkout in the same manner as I've been adding other samples like bodyweight, calories burned, etc. I'm receiving the error: HKWorkout: Sample of type HKQuantityTypeIdentifierWorkoutEffortScore must be related to a workout I tried adding the samples using HKWorkoutBuilder.add([samples]) as which has been working perfectly for calories burned & bodyweight, but I am receiving the above error for workoutEffortScore As a second approach, I tried adding the sample after I called finishWorkout on the HKWorkoutBuilder and received back the HKWorkout object using HKHealthStore.add([samples], to: HKWorkout) and am still receiving the same error! I don't know otherwise how to relate a sample to a workout, I thought those were the APIs to do so? I'm using Xcode 16.0 RC (16A242) and testing on an iOS 16 Pro simulator
5
1
1.3k
1w
HealthKit - HKWorkoutRouteBuilder never returns from insert when created from newly added iOS HKLiveWorkoutBuilder API on Simulator
Has anyone had success using the HKWorkoutRouteBuilder in conjunction with the new iOS support for HKLiveWorkoutBuilder? I was running my watchOS code that worked now brought over to iOS and when I call insertRouteData the function never returns. This happens for both the legacy and closure based block patterns. private var workoutSession: HKWorkoutSession? private var workoutBuilder: HKLiveWorkoutBuilder? private var serviceSession: CLServiceSession? private var workoutRouteBuilder: HKWorkoutRouteBuilder? private func startRouteBuilder() { Task { @MainActor in self.serviceSession = CLServiceSession(authorization: .whenInUse) self.workoutRouteBuilder = self.workoutBuilder?.seriesBuilder(for: .workoutRoute()) as? HKWorkoutRouteBuilder self.locationUpdateTask = Task { do { for try await update in CLLocationUpdate.liveUpdates(.fitness) { if let location = update.location { self.logger.notice(#function, metadata: [ "location": .stringConvertible(location) ]) try await self.workoutRouteBuilder?.insertRouteData([location]) self.logger.notice("Added location") } } } catch { self.logger.error(#function, metadata: [ "error": .stringConvertible(error.localizedDescription) ]) } } } } I did also try CLLocationManager API with delegate which is what my current watch code uses (a bit old). Same issue. Here is what I've found so far: If the workout session is not running, and if the builder hasn't started collection yet, inserting route data works just fine I've tried different swift language modes, flipped from main actor to non isolated project settings (Xcode 26) Modified Apple's sample code and added location route building to that and reproduced the error, modified sample attached to feedback This issue was identified against Xcode 26 beta 2 and iPhone 16 Pro simulator. Works as expected on my iPhone 13 Pro beta 2. FB18603581 - HealthKit: HKWorkoutRouteBuilder insert call within CLLocationUpdate task never returns
0
0
118
2w
Incorrect Step Count from Apple HealthKit Data
Hi, i'm trying to get the number of step counts a person has taken. I decided to pull the data from health kit and the number of steps are incorrect. Come to find out apple health recommends an app called pedometer++ for the number of steps counted and after testing I realized that they are getting the correct number of steps a person is taking. How can I pull the correct number of steps a person has taken? I want to be able to merge the data from watch and phone to make sure we are getting the correct number of steps but not double counting the steps either. any guidance on this would be appreciated! Here's the code snippet that i'm using right now: permissions: { read: [AppleHealthKit.Constants.Permissions.StepCount], write: [], }, }; AppleHealthKit.initHealthKit(permissions, error => { if (error) { console.log('Error initializing HealthKit: ', error); return; } else { dispatch(setAllowHealthKit(true)); getHealthKitData(); console.log('HealthKit initialized successfully'); } }); const getHealthKitData = async () => { try { const today = new Date(); const options = { startDate: new Date(today.setHours(0, 0, 0, 0)).toISOString(), endDate: new Date().toISOString(), }; const steps = await new Promise((resolve, reject) => { AppleHealthKit.getStepCount(options, (error, results) => { if (error) reject(error); resolve(results?.value); }); }); setStepsCount(steps); } catch (error) { console.error('Error fetching HealthKit data:', error); } };
6
0
128
2w
Statistics collection query first result returned is wrong
I'm reading hourly statistics from HealthKit using executeStatisticsCollectionQuery (code below). Expectation What I expect is to get back the list with one row per hour, where each hours has the same cumulative sum value. Actual result In results, first hour always contains less calories than next hours, which all have the same value. Example: Start: 2025-06-02T00:00:00+03:00, anchor: 2025-06-02T00:00:00+03:00, end: 2025-06-02T12:00:00+03:00 🟡 2025-06-02T00:00:00+03:00 Optional(50.3986 kcal) 🟡 2025-06-02T01:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T02:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T03:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T04:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T05:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T06:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T07:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T08:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T09:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T10:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T11:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T12:00:00+03:00 Optional(14.0224 kcal) As you can see, here we have 2025-06-02T00:00:00+03:00 Optional(50.3986 kcal) Now, if I add one more hour to the request (from beginning of time window), the same hour has proper calories count, while newly added hour, has wrong value): 2025-06-01T23:00:00+03:00, anchor: 2025-06-01T23:00:00+03:00, end: 2025-06-02T12:00:00+03:00. 🟡 2025-06-01T23:00:00+03:00 Optional(50.3986 kcal) 🟡 2025-06-02T00:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T01:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T02:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T03:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T04:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T05:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T06:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T07:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T08:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T09:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T10:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T11:00:00+03:00 Optional(64.421 kcal) 🟡 2025-06-02T12:00:00+03:00 Optional(14.0224 kcal) And now first hour of the day, magically has more calories burned: 2025-06-02T00:00:00+03:00 Optional(64.421 kcal) I suspect similar things happen with other quantity types, but haven't yet found a way to reproduce it. Am I doing something wrong or is it a bug in HealthKit? Code let anchorDate = startDate let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [.strictStartDate]) healthStore.executeStatisticsCollectionQuery( quantityType: .basalEnergyBurned, quantitySamplePredicate: predicate, options: [.separateBySource, .cumulativeSum], anchorDate: anchorDate, intervalComponents: DateComponents(hour: 1), initialResultsHandler: { statistics, error in if let error = error { log(.error, "Error retrieving steps: \(error.localizedDescription)") continuation.resume(throwing: SpikeException("Error retrieving steps: \(error.localizedDescription)")) return } if let statistics { let f = ISO8601DateFormatter() f.timeZone = TimeZone.current for s in statistics { log(.debug, "\(f.string(from: s.startDate)) \(s.sumQuantity())") } } continuation.resume(returning: statistics ?? []) } )
2
0
50
2w
Fitness app not now show saved routes
When I set the distanceFilter = 5 (5 meters) in the GPS CLLocationManager I can't display the workout routes in the Apple Fitness app after writing the recorded GPS data to HealthKit via HKWorkoutRouteBuilder. The smaller distanceFilter, Fitness will displays the route. Should I consider setting up a small distanceFilter when developing a workout app on watchOS?
5
0
83
2w
What’s the expected frequency of HealthKit enableBackgroundDelivery: HKCategoryTypeIdentifier.sleepAnalysis
Hello, I have enabled HealthKit background delivery for sleep analysis samples: private func setupSleepDataBackgroundDelivery() { if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) { healthStore.enableBackgroundDelivery(for: sleepType, frequency: .immediate) { (success, error) in } } } In general, this function works. But I would love to know what the limitations / expected delivery delay for frequency: .immediate is. The documentation is only very vague about this and specifies that some sample types such as steps are only delivered once per hour. But how about sleep data? Is this expected to be delivered immediately once available on iPhone? Thanks a lot for your help!
1
1
136
2w
Guideline 1.4.1 - Safety - Physical Harm
Hello everyone, my app is designed to help people sleep. It has been rejected multiple times due to issues with version 1.4.1 during the submission process. However, the app simply evaluates users’ insomnia and anxiety status based on their responses to questions and provides some relaxation methods. It does not involve any medical-related content. The reviewer provided screenshots of the assessment results page and some relaxation techniques. How should I handle this issue?
2
0
85
2w
Guideline 1.4.1 - Safety - Physical Harm
Hello everyone, my app is designed to help people sleep. It has been rejected multiple times due to issues with version 1.4.1 during the submission process. However, the app simply evaluates users’ insomnia and anxiety status based on their responses to questions and provides some relaxation methods. It does not involve any medical-related content. The reviewer provided screenshots of the assessment results page and some relaxation techniques. How should I handle this issue?
0
0
21
3w
Evolution of HealthKit workout API on iOS 26 and iPadOS 26 - HKLiveWorkoutDataSource and built-in Sensor Support
I am very happy to see that HealthKit with OS26 is bringing HKLiveWorkoutDataSource to iOS and iPadOS. I have been replicating a similar type for the last several years for users that only have an iPhone. I did notice that the data types that the different platform data sources collect automatically is different. That makes sense if you think exclusively about what the device can actually capture. Bluetooth HRM is the only Bluetooth SIG profile that is out-of-the-box supported for Apple Health on iOS and iPadOS (right?). Whereas watchOS 10 got all of the cycling sensors (woohoo!). It would be great if the types to collect were the same across platforms even if the device couldn't collect the data now, because then in the future when / if new sensor support is added, it will be transparent to developers. Fantastic. Easier life as an indie / third party developer. At least that is the idea. And yes, I know I can also write Core Bluetooth code and roll my own SIG implementation for the cycling profiles, but Apple already has this code in one os, 'just copy it, it will be easy'. I know that isn't the reality especially against the new ASK framework, but one can hope and dream right? Imagine how many more apps would contribute that data if it was supported out of the box. An alternative, GitHub is a great place for Apple to share their Core Bluetooth implementation of the SIG profiles :). Just another thought. Here are some feedbacks related to this: FB17931751 - HealthKit: Add built-in support for cycling sensors on iOS and iPadOS - copy paste the code from watchOS. It will be easy they said (June 2025) FB12323089 - CoreBluetooth / Health / Bluetooth Settings: Add support for cycling sensors announced in watchOS 10 to iOS and iPadOS 17 (June 2023) FB14311218 - HealthKit: Expected outdoor cycling to include .cyclingSpeed quantity type as a default HKLiveWorkoutDataSource type to collect (July 2024) FB14978701 - Bluetooth / HealthKit / Fitness: Expose information about the user specified for Apple Watch paired Cycing Speed Sensor like isConnected and wheelCircumference values (August 2024) FB18402258 - HealthKit: HKLiveWorkoutDataSource should collect same types on iOS and watchOS even if device cannot produce data today (June 2025) FB14236080 - Developer Documentation / HealthKit: Update documentation for HKLiveWorkoutDataSource typesToCollect for which sample types are automatically collected by watchOS 10 and 11 (July 2024) Tangentially related: FB10281304 - HealthKit: Add HKActivityTypes canoeBikeRun and kayakBikeRun (June 2022) FB10281349 - HealthKit: Add HKActivityType walkCanoeWalk and walkKayakWalk (June 2022) FB7807993 - Add HKQuantityTypeIdentifier.paddleDistance for canoeing, kayaking, etc type workouts (June 2020) FB12508654 - HealthKit / Settings / Bluetooth / Workouts: Cycling sensor support doesn't allow for 'bike selection' in use case of multiple bikes and multiple sensors (borrow a bike to ride together) - production usability issue (July 2023)
0
1
87
3w
Apple Watch Data to Server
I was wondering which is the preferred way to send a lot of data from sensors of the apple watch to server. It is preferred to send small chucks to iphone and then to server or directly send bulk data to server from watch. How does it affect battery and resources from watch ? Are there any triggers that I can use to ensure best data stream. I need to send at least once a day. Can I do it in background or do I need the user to have my app in the foreground ? Thank you in advance
1
0
71
Jun ’25
Real-Time WatchConnectivity Sync Not Working Between iPhone and Apple Watch
Hi everyone, I'm building a health-focused iOS and watchOS app that uses WatchConnectivity to sync real-time heart rate and core body temperature data from iPhone to Apple Watch. While the HealthKit integration works correctly on the iPhone side, I'm facing persistent issues with WatchConnectivity — the data either doesn't arrive on the Watch, or session(_:didReceiveMessage:) never gets triggered. Here's the setup: On iPhone: Using WCSession.default.sendMessage(_:replyHandler:errorHandler:) to send real-time values every few seconds. On Apple Watch: Implemented WCSessionDelegate, and session(_:didReceiveMessage:) is supposed to update the UI. Both apps have WCSession.isSupported() checks, activate the session, and assign delegates correctly. The session state shows isPaired = true and isWatchAppInstalled = true. Bluetooth and Wi-Fi are on, both devices are unlocked and nearby. Despite all this, the Watch never receives messages in real-time. Sometimes, data comes through in bulk much later or not at all. I've double-checked Info.plist configurations and made sure background modes include "Uses Bluetooth LE accessories" and "Background fetch" where appropriate. I would really appreciate guidance on: Best practices for reliable, low-latency message delivery with WatchConnectivity. Debugging steps or sample code to validate message transmission and reception. Any pitfalls related to UI updates from the delegate method. Happy to share further details. Thanks in advance!
1
0
41
Jun ’25
Stands not detected
I have FB12696743 open since July 21, 2023 and this happened again today. I get home at approx 10 mins after the hour, walk appox 50 ft across my yard, up 5 steps into my house, let the dog out and pace on my deck watching the dog, go back in the house walk around the kitchen while preparing dinner. A total of about 200 ft. I sit down about 35 past the hour and start to eat and at 10 mins to the next our and I get the reminder to stand. On the other side I wake up at 5 mins to hour. Walk 8 steps to the bathroom and successfully achieve the stand for that hour. WHY!?!?!? 😁🤣
1
1
461
Jun ’25
Healthkit - Oura Sync Issue
We are working on the health related application and use apple health kit to sync the data from different devices like watches or ring. We are targeting oura ring to get sleep and other parameters data. We are able to sync the data from oura for all other parameters (like pulse, respiratory rate, blood pressure, etc..) other than sleep. Surprisingly, sleep data that comes through other devices is syncing as expected from the health kit. We are even getting the data which is added manually in health kit. The only sleep data not syncing is from oura. Can we get a document or any kind of help to sync the data from oura in to our application using health kit?
0
0
52
May ’25