HealthKit

RSS for tag

Access and share health and fitness data while maintaining the user’s privacy and control using HealthKit.

Posts under HealthKit tag

94 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

HealthKit: Exercise Minutes Not Saving After iOS 18.1 Update
I'm working on an app that reads and writes exercise minutes to HealthKit. Everything functions correctly up to iOS 18.0.1, but starting from iOS 18.1, my implementation is no longer working as expected. Here's the code snippet I use to write to HealthKit: let workout = HKWorkout(activityType: .other, start: startDate, end: endDate) try await healthStore.save(workout) This code successfully writes to both workouts and exercise minutes in iOS 18.0.1 and earlier. However, from iOS 18.1, it only writes to workouts and not to the exercise minutes data source. Has anyone encountered this issue or have insights on how to resolve this?
0
0
96
4d
HKCumulativeQuantitySample does not accumulate values
Hi, My app reports daily step counts, and I’m trying to use HKCumulativeQuantitySample to report them to HealthKit by adding such objects with each update: let sample = HKCumulativeQuantitySample(type: .stepCount, quantity: HKQuantity(unit: HKUnit.count(), doubleValue: dailyTotal), start: startOfDay, end: nowDate) However, HealthKit interprets them as regular samples—it sums them into a global aggregate instead of updating the daily cumulative value. So if I report the daily step count as 500 and then 550, HealthKit interprets it as 1,050 steps instead of 550. Is this expected behavior? If so, what is HKCumulativeQuantitySample intended for, and how should it be used? I’m struggling to find any examples. Thank you
0
0
140
2w
Unable to retrieve certain data during live workout
I'm currently trying to collect some of the following data whilst running a workout in a WatchOS app I'm building. Below are the data points I'm trying to retrieve: HKQuantityType.init(.heartRate) HKQuantityType.init(.oxygenSaturation) HKQuantityType.init(.respiratoryRate) HKQuantityType.init(.bloodPressureSystolic) HKQuantityType.init(.bloodPressureDiastolic) HKQuantityType.init(.heartRateVariabilitySDNN) I'm using the following delegate function workoutBuilder(_:didCollectDataOf:) which is part of HKLiveWorkoutBuilderDelegate Something I'm realising whilst running this on the simulator and on my Apple Watch is out of all of the Quantity types I'm requesting. Only the heart rate is being called via the delegate function when trying to retrieve the statistic. Is this the intended behaviour of this API? Since there's no docs about what is and isn't exposed
0
0
158
2w
iCloud Health data not syncing properly with iPhone Simulator on MacOS
As the title says, I logged in to iCloud on my simulator on my mac mini m2 and turned on icloud sync. My health data is in iCloud but it wont load in. When I go to documents for example I can see documents that I have loaded so I know something is working right. I have tried clicking Feature -> Trigger iCloud sync with no luck. I have tried logging out and logging back in, no luck. I have tried Restarting the simulator with no luck. The app I am building uses health data and there is no other way to get health data (heart rate, workouts, sleep) in the simulator. Please help, Thank you
1
1
169
1w
iCloud Health data not syncing to simulator
As the title says, I logged in to my simulator on my mac mini m2 and turned on icloud sync. My health data is in iCloud but it wont load in. When I go to documents for example I can see documents that I have loaded so I know something is working right. I have tried clicking Feature -> Trigger iCloud sync with no luck. The app I am building uses health data and there is no other way to get health data (heart rate, workouts, sleep) in the simulator. Please help
0
0
127
2w
Walking speed
I´m working within the health felid with a few apps. Accordingly to science one of the most important parts to keep healthy is every day walking. But it is not to walk slow. You need to come to a little speed (not running or even jogging). But to rais your puls. This is when you get the "real health effect". In general it is around 6km/h. It would be great if apple could make this info available for us developers. I think lots of developers will be happa and use this to make better apps and get more people in a healtheyer life. Looking forward to get some feedback on this. Thank you! Cheers Peter
1
0
125
3w
Sleep Analysis inBed sample not recorded on Apple Watch in iOS 18
In this link, Apple states we can know when a user is in bed vs sleeping and compare their quality of sleep by it. Only, in iOS 18, Apple no longer reports inBed time samples for the Apple Watch. I get why they stopped doing this for the phone, but why the watch? Bug? My app was using the inBed times for this very purpose and now only works for Garmin and Oura who still report inBed times. https://developer.apple.com/documentation/healthkit/hkcategoryvaluesleepanalysis
0
0
171
3w
Seeking Feedback on an Idea: Real-Time Siri Running Coach for iOS
Hello everyone, I hope you’re all doing well. I’m not a developer, but I have an idea for an iOS app that I’d love to get your thoughts on. I wanted to share it here to gather feedback from this knowledgeable community and to learn from your expertise. Idea Overview: Real-Time AI Running Coach for iOS The concept is an iOS application that provides personalized, real-time running coaching by leveraging on-device data sources and Apple’s latest technologies. The app aims to offer an adaptive and motivating running experience while ensuring user privacy through on-device processing. Key Features: • Personalized Coaching: • Utilize real-time biometric data and personal insights to deliver AI-driven coaching tailored to the user’s mental and physical state. • Analyze health metrics, activity data, mood check-ins, and more to provide context-based motivational feedback. • Privacy First: • All data processing occurs on-device using Apple’s frameworks like Core ML, ensuring no personal data leaves the device. • Adaptive Motivation: • Implement Natural Language Processing to analyze user inputs like journal entries or mood check-ins. • Generate personalized coaching cues based on historical performance and mood trends. • Performance Enhancement: • Offer dynamic adjustments to pace, route, and strategy in real time to help improve running performance. • Seamless integration with Apple Watch for real-time data collection and haptic feedback. Technologies and Frameworks Involved: • HealthKit: Access health metrics such as heart rate, distance run, VO₂ max, sleep patterns, etc. • Core ML: On-device machine learning for real-time data analysis without latency. • Natural Language Processing: Analyze personal inputs for better coaching personalization. • Core Motion & Core Location: Track motion data and location services for runs. • AVFoundation & Speech: Provide real-time voice feedback and coaching cues. • SiriKit Integration: Allow users to initiate workouts and receive updates via Siri. Target Audience: • Runners of all levels seeking personalized coaching that adapts to their mental and physical states. • Users who prioritize privacy and want AI-driven insights without their data leaving the device. • Tech-savvy fitness enthusiasts who use iOS devices and Apple wearables. Questions for the Community: 1. Feasibility: Is this idea technically achievable using current iOS frameworks and technologies? 2. Data Access: Are there limitations in accessing and processing the necessary data on-device, especially regarding privacy and permissions? 3. Potential Challenges: What hurdles might developers face in creating such an app, and how could they be addressed? 4. Advice: As someone without a technical background, what steps would you recommend I take to move this idea forward? I truly appreciate any feedback or insights you can provide. I’m excited about the potential of this idea but also aware there may be complexities I’m not considering. Thank you for taking the time to read this! Best regards, Paul
0
0
208
4w
How to send a simple request when HKObserverQuery triggered in background?
Hi everyone, I am trying to send a request to my server in my watch application when HKObserverQuery is triggered. This is working fine when my app is in foreground however the request is not sending when the app manually terminated or in background. HKObserverQuery works fine and triggered in these cases however the request is not sending. I researched about URLSessionConfiguration.background and background sessions but I could not figure it out. I don't want to download or upload a file, I just want to send a simple request when HKObserverQuery is triggered. Can you show me to a path way to make it possible? I am trying to test my watch app with my iPhone, I am assuming the behavior of these scenarios might be same in both device, am I correct? let urlsession = URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "enablement"), delegate: self, delegateQueue: nil) let dataTask = urlsession.dataTask(with: urlRequest) dataTask.resume() As shown in the code snippet, I tried to set background configuration to my URLSession. I enabled background fetch in background modes. Apple documentation says, dataTask can not run in background -> https://developer.apple.com/documentation/foundation/urlsessiontask However I don't want to perform a long running task such as downloading or uploading.
3
0
297
Oct ’24
HealthKit data - Is HKStatisticsCollectionQuery slow?
Hi, I am using HealthKit for the first time. I am using HKStatisticsCollectionQuery. I am running my code iOS 17 on a physical iPhone. It takes several seconds to query data, for example 1 day worth of heart rate at 1 minute resolution. I changed the resolution to 1 hour, expecting it to be faster, but it's pretty much the same… I have been following the official documentation and sample code. I also compiled in Release, but that didn't really help for HKStatisticsCollectionQuery. I quickly looked with Instruments, the app is spending a lot of time in decoding data with NSXPCDecoder. Is there a way to speed data retrieval? Or this is "expected" latency?
2
0
305
Oct ’24
Healthkit HKWorkoutSession state not transitioning
Im building a workout app to track swimming workouts for watchos 11. Triggering .prepare() on my HKWorkoutSession does not change the session state HKWorkoutSessionState. Below is my prepare function which should transition the session state to HKWorkoutSessionStatePrepared. Nothing is thrown in the delegates, the state just wont change? I have tried erasing, restarting, use another version of xcode and another simulator runtime. func prepare() { guard self.session == nil else { fatalError("Session already exist") } // Configure Workout Type let config = HKWorkoutConfiguration() config.activityType = .swimming config.swimmingLocationType = .openWater config.locationType = .outdoor self.Workoutconfig = config // Create Session do { guard store.authorizationStatus(for: .workoutType()) == .sharingAuthorized else { fatalError("Lack of permission to start workout") } let session = try HKWorkoutSession(healthStore: store, configuration: config) self.session = session self.builder = session.associatedWorkoutBuilder() Logger.diveController.info("Successfully created workout session") builder?.dataSource = HKLiveWorkoutDataSource(healthStore: store, workoutConfiguration: config) self.session?.delegate = self self.builder?.delegate = self if self.session == nil { fatalError("No workout session created") } if self.builder == nil { fatalError("No workout builder created") } self.session?.prepare() logger.debug("Session Started at: \(self.session?.startDate ?? Date())") logger.debug("Session State: \(self.session?.state.description ?? "")") if self.session?.state != .prepared { reset() fatalError("Failed To Prepare") } } catch { Logger.diveController.error("Error starting workout session: \(error.localizedDescription)") } }
1
0
271
Oct ’24
HealthKit Read Permissions Not Displayed in Health App Settings After App Update
I am encountering a problem with HealthKit authorization in my app. In a previous version of the app, write permission for HKWorkoutType was already granted. In the new version of the app, I added a request for read permissions for both HKWorkoutType and HKWorkoutRoute. After updating the app, the following occurs: I can successfully fetch workout data using HKSampleQuery, and authorizationStatus(for: HKObjectType.workoutType()) returns .sharingAuthorized, indicating that the app has access to the data. However, when I check the Health app (Settings -> Health -> Data Access & Devices -> [App Name]), the read permission does not appear in the list. The write permission is still visible, but the newly requested read permission is missing. This behavior is unexpected because, despite being able to access the data programmatically, the read permission is not listed in the Health app settings. I have already verified that I am requesting the read permissions correctly in the code using requestAuthorization for both HKObjectType.workoutType() and HKObjectType.seriesType(forIdentifier: .workoutRoute). I would appreciate guidance on why this issue is occurring and how to ensure that read permissions are displayed correctly in the Health app settings.
1
0
206
Oct ’24
Mirroring Workouts Sample Code Doesn't Work With Simulators
I've realised with the sample code from the WWDC video below I'm getting the following error when trying to use the iPhone simulator and apple watch simulator paired. Whenever i try to test out the sample project I'm getting the following error. Failed to send data: Error Domain=com.apple.healthkit Code=300 "Remote device is unreachable" UserInfo={NSLocalizedDescription=Remote device is unreachable, NSUnderlyingError=0x600000c9c900 {Error Domain=RPErrorDomain Code=-6727 "kNotFoundErr ('rapport:rdid:PairedCompanion' not found)" UserInfo={cuErrorDesc=kNotFoundErr ('rapport:rdid:PairedCompanion' not found), cuErrorMsg='rapport:rdid:PairedCompanion' not found, NSLocalizedDescription=kNotFoundErr ('rapport:rdid:PairedCompanion' not found)}}} Is it not possible to not test out the new WorkoutKit mirroring API's using the simulator? Currently right now if you run the project you'll notice that you can start a workout session on the iPhone > Apple Watch but there is no way to control and mirror on both devices at the moment i.e You can't control the iPhone app on the Apple Watch and vice versa. Also because of this the iPhone can't send data to the Apple Watch i.e. pause, end, water etc. I'm guessing this is meant to be possible since it seems a bit strange to only be able to test this out with actual devices. WWDC Session https://developer.apple.com/wwdc23/10023 Sample Code https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/building_a_multidevice_workout_app
2
0
262
Oct ’24
Missing manual - Training Load, .estimatedWorkoutEffortScore, .workoutEffortScore - Where are the Apple RPE CR-10 scale docs?
Apple is using the RPE scale for workout effort scores. This stands for the Rate of Perceived Exertion. They're specifically using the CR-10 scale, at least from what I can tell by saving values to HealthKit. They only accept value between 0 and 10. Has anyone been able to find a scientific or academic paper on how they have chosen their different effort breakouts? Right from the Fitness app on iPhone and Activity app on Apple Watch: 1-3 Easy 4-6 Moderate 7-8 Hard 9-10 All Out There is zero documentation on these new types, which makes it difficult for workout recording apps to properly and appropriately save this new data type. Sure, we can use the Apple apps as a reference, but since there isn't a built-in Apple SwiftUI sheet to present this data, and no references to academia to point our users to, our solutions would just look the same. FB15315876 - Documentation / HealthKit: Publish documentation about .workoutEffortScore and .estimatedWorkoutEffortScore FB15316109 - Documentation / HealthKit: Add documentation to .estimatedWorkoutEffortScore and .workoutEffortScore that you can't save those samples via the save API and that they must be related and let that API save the sample FB15316251 - Documentation / HealthKit: Add documentation for acceptible values of .estimatedWorkoutEffortScore and .workoutEffortScore - don't rely on a runtime error! Apple missed making an enum for all third party developers this year.
0
1
248
Oct ’24
visionOS App Not Receiving Latest Heart Rate Data from HealthKit
Hello everyone, I'm developing an app for visionOS that utilizes HealthKit to query heart rate data. However, I'm encountering an issue where the app doesn't retrieve the latest heart rate values. Specifically, it fails to get live heart rate data even after the data has been saved to the Health app. The readings my app displays are outdated and do not match the current values shown in the Health app. Here's what I've tried so far: Fetching Heart Rate Samples: Used HKSampleQuery and HKAnchoredObjectQuery to fetch the most recent heart rate samples. Despite this, the data retrieved is still not up-to-date. Checking Permissions: Ensured that all necessary HealthKit permissions are granted. The app has authorization to read heart rate data and write workout data. My questions are: Is there a known issue or limitation with HealthKit on visionOS that prevents apps from accessing the latest heart rate data? Are there additional steps or configurations required to access live heart rate data in visionOS apps? Has anyone successfully implemented live heart rate monitoring on visionOS, and if so, could you share how you achieved it?
0
0
215
Sep ’24
Workout Effort Scores
Is there anywhere that describes in detail how third party workout apps can use the new effort score functionality? I can't see much in the documentation or any of the WWDC videos. In particular it would be useful to know if an effort score is automatically calculated for workouts created with third party apps? It doesn't seem to happen but some people say it takes weeks / months before watchOS starts calculating it for third party apps. If it doesn't happen automatically then how can the app set it? I tried the new relateWorkoutEffortSample API but that didn't work for me (see https://developer.apple.com/forums/thread/763539). If I could get it working then how should I determine a default effort score based on the workout metrics? Is that something that the app should do? If so then it would be good to be consistent with watchOS so some idea of how that is calculating effort scores would be useful. Sorry for all the questions, especially if there is an article in the documentation or a video that I have missed.
4
0
606
Oct ’24
HealthKit bugs related to new workout effort score - heart rate samples take forever to fetch, Health app displays invalid data
I am encountering issues on my device running iOS 18 that fetching heart rate samples associated to a given workout is very slow. Like 10+ seconds slow. This is unacceptable and unexpected. In producing a video to attach to a feedback, I also observed that Apple Health app displays incorrect information if a workout effort score is associated to a workout. In this image, you can see the Health app bug: Total Resting Energy != Estimated Workout Effort Score Here is the same workout after I delete the workout effort score using the Apple Health app: Can anyone else see if attempting to view 'heart rate' data within the workout summary in Apple Health is unbearably slow if that workout also has an effort score associated? My steps: Record workout (Apple Activity app on watchOS) Associate effort score View the workout on Apple Health (iOS) Attempt to view it's heart rate samples Observe very slow loading times Observe the incorrect cell label and value and disappearance of resting energy cell data Remove/disassociate the effort score from the workout by tapping the workout effort row, and swipe to delete the value. Navigate back, navigate back, and then go into the workout detail again At this time the UI fixes itself, but the loading of heart rate data is still super slow FB15269657 - HealthKit: Sample query to fetch heart rate samples associated to a workout is taking over 10 seconds - computing 'time in heart rate zone' FB15278790 - Health: Workout summary 'Total Resting Energy' label has value of 'Estimated Workout Effort Score' for a value, pushed view shows empty
0
0
315
Sep ’24
recoverActiveWorkoutSession() inaccurate for paused sessions
When a workout session is being recovered, if it is paused, the elapsed time will be incorrect. It will seem like that workout never was paused. The recovery works fine if the workout was never paused. Steps to reproduce: Implement recoverActiveWorkoutSession Start workout Pause session and print the elapsed time Stop simulator / cause crash When recoverActiveWorkoutSession is called the elapsed time will not equal the elapsed time when the session was paused. Here is my implementation. I haven't seen any examples online. guard let recovered = try? await healthStore.recoverActiveWorkoutSession() else {return} self.session = recovered self.builder = recovered.associatedWorkoutBuilder() self.session?.delegate = self self.builder?.delegate = self self.builder?.dataSource = HKLiveWorkoutDataSource(healthStore: healthStore, workoutConfiguration: recovered.workoutConfiguration) self.sessionState = recovered.state
1
0
299
Sep ’24
What's the correct way to check for unavailable API?
I ran into a problem recently with my production app and an update for iOS 18. In this example I was using a new API added to the RC candidate of iOS 18.0, using this API as an example, I couldn't find a satisfactory way to avoid crashing on iOS 18.1 where the API was not available. I had plenty of users running the iOS 18.1 Beta and ultimately it's my fault if a version of my app did work, and then didn't after an update.... This code causes a crash on iOS 18.1 beta as the .appleSleepingBreathingDisturbances API doesn't seem to have made it's way into the beta: if #available(iOS 18.0, *), #available(watchOS 11, *) { healthKitTypesToRead.insert(HKQuantityType.quantityType(forIdentifier: .appleSleepingBreathingDisturbances)!) } I tried this but it still crashed on 18.1: if #available(iOS 18.0, *), #available(watchOS 11, *) { if let newQuantity = HKQuantityType.quantityType(forIdentifier: .appleSleepingBreathingDisturbances) { healthKitTypesToRead.insert(newQuantity) } } In the end the only way I could resolve this was the following: if #available(iOS 18.1, *){ // Do nothing } else if #available(iOS 18.0, *), #available(watchOS 11, *) { if let newQuantity = HKQuantityType.quantityType(forIdentifier: .appleSleepingBreathingDisturbances) { healthKitTypesToRead.insert(newQuantity) } } This seems like a poor solution and I'll have to ensure I release a new version of the app once iOS 18.1 has the available API added to enable support for the feature. How could I have checked availability for this API correctly without causing the app to crash? I'm asking this question more as a Swift language feature rather than issue with the specific API as I'm sure that will get resolved soon anyway. Thanks
4
1
529
Sep ’24