Health & Fitness

RSS for tag

Explore the technical aspects of health and fitness features, including sensor data acquisition, health data processing, and integration with the HealthKit framework.

Health & Fitness Documentation

Posts under Health & Fitness subtopic

Post

Replies

Boosts

Views

Activity

watchOS: Is there a public API to initiate an HRV measurement?
I'm developing a watchOS meditation app in which the user starts one continuous meditation session. During that session, I'd like the app to obtain a 1-minute HRV measurement immediately after the session begins (to establish a baseline), and then automatically obtain another 1-minute HRV measurement approximately 6 minutes after the session started, without requiring the user to manually start a second measurement or leave the app. My understanding is that HealthKit allows apps to read HRV samples after they have been recorded, but I haven't found a way to request that the watch generate a new HRV measurement. Is there any public API that allows a third-party watchOS app to initiate an HRV measurement similar to the Mindfulness/Breathe app, or otherwise request the Apple Watch to collect a new HRV sample at predetermined times during an ongoing session? Thanks in advance, Hern
0
0
87
5d
Accuracy of IBI Values Measured by Apple Watch
I am currently developing an app that measures HRV to estimate stress levels. To align the values more closely with those from Galaxy devices, I decided not to use the heartRateVariabilitySDNN value provided by HealthKit. Instead, I extracted individual interbeat intervals (IBI) using the HKHeartBeatSeries data. Can I obtain accurate IBI data using this method? If not, I would like to know how I can retrieve more precise data. Any insights or suggestions would be greatly appreciated. Here is a sample code I tried. @Observable class HealthKitManager: ObservableObject { let healthStore = HKHealthStore() var ibiValues: [Double] = [] var isAuthorized = false func requestAuthorization() { let types = Set([ HKSeriesType.heartbeat(), HKQuantityType.quantityType(forIdentifier: .heartRateVariabilitySDNN)!, ]) healthStore.requestAuthorization(toShare: nil, read: types) { success, error in DispatchQueue.main.async { self.isAuthorized = success if success { self.fetchIBIData() } } } } func fetchIBIData() { var timePoints: [TimeInterval] = [] var absoluteStartTime: Date? let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(identifier: "Asia/Seoul") dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" var calendar = Calendar.current calendar.timeZone = TimeZone(identifier: "Asia/Seoul") ?? .current var components = DateComponents() components.year = 2025 components.month = 4 components.day = 3 components.hour = 15 components.minute = 52 components.second = 0 let startTime = calendar.date(from: components)! components.hour = 16 components.minute = 0 let endTime = calendar.date(from: components)! let predicate = HKQuery.predicateForSamples(withStart: startTime, end: endTime, options: .strictStartDate) let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false) let query = HKSampleQuery(sampleType: HKSeriesType.heartbeat(), predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sortDescriptor]) { (_, samples, _) in if let sample = samples?.first as? HKHeartbeatSeriesSample { absoluteStartTime = sample.startDate let startDateKST = dateFormatter.string(from: sample.startDate) let endDateKST = dateFormatter.string(from: sample.endDate) print("series start(KST):\(startDateKST)\tend(KST):\(endDateKST)") let seriesQuery = HKHeartbeatSeriesQuery(heartbeatSeries: sample) { query, timeSinceSeriesStart, precededByGap, done, error in if !precededByGap { timePoints.append(timeSinceSeriesStart) } if done { for i in 1..<timePoints.count { let ibi = (timePoints[i] - timePoints[i-1]) * 1000 // Convert to milliseconds // Calculate absolute time for current beat if let startTime = absoluteStartTime { let beatTime = startTime.addingTimeInterval(timePoints[i]) let beatTimeString = dateFormatter.string(from: beatTime) print("IBI: \(String(format: "%.2f", ibi)) ms at \(beatTimeString)") } self.ibiValues.append(ibi) } } } self.healthStore.execute(seriesQuery) } else { print("No samples found for the specified time range") } } self.healthStore.execute(query) } }
3
0
247
1w
HealthKit Time in Daylight: sample granularity, latency, and relationship to Health app values
Hi, We are integrating HKQuantityTypeIdentifierTimeInDaylight into a research application and have a few questions about how developers should interpret the data returned by HealthKit. Specifically: Should TimeInDaylight samples be treated as having a fixed minimum temporal granularity (for example, approximately 5-minute intervals), or is the sample duration implementation-dependent and subject to change? Is there any expected latency between a daylight exposure event and the corresponding TimeInDaylight sample becoming available through HealthKit? For example, are samples intended to appear shortly after exposure, or only after periodic processing and synchronization? In the Health app, each Time in Daylight sample displays a Maximum Light Intensity (lux). Is this value available through the public HealthKit API (e.g., metadata), or is it only used internally by the Health app? More generally, should developers consider TimeInDaylight to be a high-level derived metric rather than expecting a direct correspondence with underlying ambient light sensor observations? Thank you.
0
0
133
1w
technical clarification on sensorkit measurement sampling
Dear SensorKit team, We are currently working with SensorKit ambient light data under our approved SensorKit entitlement for research use. We would be grateful for some technical clarification on the sampling strategy for the SRSensor.ambientLightSensor stream, as this directly affects how we analyse and report the data. In exported data from Apple Watch, we observe that ambient light samples do not appear to follow a fixed sampling cadence. Instead, the data appear burst-like: in one short window, we see many samples with inter-sample intervals around 100 ms, occasional near-duplicate timestamps, and then gaps of around 10 to 30 seconds with no samples. This suggests that the stream may be adaptive, event-triggered, buffered, or subject to system-level sampling decisions. We also noticed a related discrepancy when comparing the SensorKit ambient light trace with the Health app display for a corresponding Time in Daylight sample. In one example, the Health app shows a 5-minute Time in Daylight interval with a “Maximum Light Intensity” value of 9,493 lux. In the SensorKit ambient light trace around that period, the raw samples show a different maximum depending on the precise time window considered, including higher values shortly before the HealthKit interval start and lower values within the subset of SensorKit samples we inspected. We realise that Time in Daylight may be generated by a separate internal aggregation or classification pipeline, but this comparison raised the question of how closely SensorKit ambient light samples should be expected to correspond to the light intensity values displayed in Health. Could you clarify the following points for SensorKit ambient light data? Is SRSensor.ambientLightSensor sampled at a fixed cadence, or is sampling adaptive / event-driven? If sampling is adaptive, what factors influence sampling density? For example, changes in illuminance, device or wrist motion, device orientation, display state, app state, power state, charging state, or other system-level conditions. Are ambient light readings buffered and delivered or exported in bursts? Do SensorKit timestamps correspond to the physical sensor acquisition time, processing time, or the time at which the sample is made available through SensorKit? Are duplicate or near-duplicate ambient light samples expected in SensorKit exports? Are there circumstances under which ambient light sampling is suspended, downsampled, or suppressed? Is SensorKit ambient light expected to match, approximate, or differ from the light intensity values shown in Health app Time in Daylight sample details? Is the “Maximum Light Intensity” shown for Time in Daylight computed from the same underlying ambient light sensor stream exposed through SensorKit, or from a separate internal stream or aggregation? Are there recommended practices for analysing SensorKit ambient light data, especially with respect to irregular sampling, burst sampling, missing intervals, and aggregation to longer time windows? Is the sampling strategy the same across Apple Watch hardware versions, or should researchers expect device-specific differences? We do not need proprietary implementation details. Our goal is to understand the methodological constraints well enough to analyse the data appropriately and describe the limitations accurately in scientific work. Thank you!
2
0
339
1w
HKWorkoutBuilder.finishWorkout() fails silently (nil workout, nil error) when device is locked (iOS 26.4+)
Hello everyone, We are encountering a critical regression introduced in iOS 26.4 that results in permanent workout data loss for users. When invoking HKWorkoutBuilder.finishWorkout(completion:) while the iOS device is locked, the save operation fails completely. However, it fails silently: the completion handler executes but returns both a nil workout and a nil error. Expected Behavior: Before iOS 26.4 finishWorkout resulted in a workout id, and correctly stored the workout data in HealthKit. According to HealthKit data protection documentation, saving data when the device is locked should either succeed (writing to a temporary journal file to be merged upon unlock) or explicitly throw an error such as HKError.Code.errorDatabaseInaccessible. Actual Behavior: Because the framework returns nil for both the object and the error, the application has no way to detect that the save failed. We cannot implement a retry mechanism or queue the save, resulting in silent data loss. Steps to Reproduce: We have built a Minimal Reproducible Example (MRE) that reliably triggers this: Initialize an HKWorkoutBuilder and call beginCollection(withStart:) followed by endCollection(withEnd:). Wrap the finishWorkout call in a short 5-second asynchronous delay, protected by a UIBackgroundTask to prevent app suspension. Lock the physical device during this 5-second window. The finishWorkout completion handler will execute while the device is locked, returning workout == nil and error == nil. Existing Reports: We have filed this via Feedback Assistant (a month ago) and opened a TSI (a week ago), providing the MRE project and a sysdiagnose captured at the time of failure: Feedback ID: FB22396180 TSI Case-ID: 19755043 As we have not yet received a response or a suggested workaround through these official channels, we are reaching out to the community. Has anyone else encountered this silent failure with HKWorkoutBuilder recently? Any insights or escalation help would be greatly appreciated.
6
2
773
1w
Please add Sleep Tracking support for Family Setup Apple Watches
Hi everyone, I’d love to see Apple add full Sleep Tracking support for Apple Watches that are set up using Family Setup. Many families use Family Setup for children or older family members who don’t have an iPhone of their own. Sleep is one of the most important health metrics, and it would be incredibly useful if caregivers could view sleep duration and trends just like they can with other health features. This would help parents better understand their child’s sleep habits and would also be valuable for families caring for older adults. Even if detailed health data stayed private, allowing sleep summaries to sync through Family Setup would make the feature much more useful. I hope Apple considers adding this in a future watchOS update. Is this something anyone else would find helpful?
0
0
148
1w
HKStatisticsCollectionQueryDescriptor intermittently returns no data for certain date ranges on iOS 27
We are seeing inconsistent results from HKStatisticsCollectionQueryDescriptor on iOS 27. Using the same quantity type, statistics options, anchor date, interval components, and predicate configuration, some date ranges return the expected statistics, while other ranges unexpectedly return empty results or buckets with no quantity. The affected ranges do contain HealthKit samples: HKSampleQueryDescriptor finds samples in the same date range. HKStatisticsQueryDescriptor returns the expected value when run separately for an affected bucket. HKStatisticsCollectionQueryDescriptor returns no quantity for that same bucket. Slightly expanding or shifting the date range may cause the collection query to return data again. A simplified version of the query looks like this: let datePredicate = HKQuery.predicateForSamples( withStart: startDate, end: endDate, options: .strictStartDate ) let descriptor = HKStatisticsCollectionQueryDescriptor( predicate: .quantitySample( type: quantityType, predicate: datePredicate ), options: .cumulativeSum, anchorDate: anchorDate, intervalComponents: DateComponents(day: 1) ) let collection = try await descriptor.result(for: healthStore) collection.enumerateStatistics(from: startDate, to: endDate) { statistics, _ in let quantity = statistics.sumQuantity() print(statistics.startDate, quantity as Any) } Expected behavior Every interval containing matching samples should return the corresponding statistics, regardless of the overall requested date range. Actual behavior Some date ranges produce missing or empty buckets even though matching samples exist and an individual HKStatisticsQueryDescriptor can calculate the expected value. Changing only the date range can make the data appear or disappear. The samples are visible to the app in the affected range, so this does not appear to be explained solely by iOS 27’s Limited History authorization. This behavior was not observed with the same query flow on earlier iOS versions. Is this a known regression in HKStatisticsCollectionQueryDescriptor on iOS 27, or has the expected date-range or predicate behavior changed?
0
0
204
2w
Track workouts with HealthKit on iOS + GPS tracking
I've built an iOS app according to this WWDC25 video (https://developer.apple.com/videos/play/wwdc2025/322). I added GPS tracking for workouts. In Xcode, I've enabled Signing & Capabilities > Background Modes: Location Updates. And in my code, I request CLAuthorisationStatus.authorizedAlways. Everything works as expected, but I am unsure if .authorizedWhenInUse will not be sufficient for this kind of app. It seems even to work when I use .authorizedWhenInUse as either the Dynamic Island or the Live Activity is shown when the app is not in the foreground. I need clarification by an expert.
1
0
576
2w
National early warning system for sepsis
this may be too hard to achieve at the moment. sepsis can develop very quickly News2 is an app available on the store that measures the components of sepsis - pulse rate, blood pressure,respiratory rate, oxygen levels, temperature and conscious level - new confusion, it was developed by the royal college of physicians. some of these things can be measured on an Apple Watch. I am not a doctor, but I wonder if it would be possible to develop something for a watch that would prompt the wearing to think about it or even ask are you ok and manage in a similar way to it looks like you have had a fall. it might mean the wearer adding more information into Apple health, for instance whether they have Copd, use oxygen etc, so the system has a baseline jus a thought, and the rcp would be the best people to contact regarding the efficacy of this, but if it could be added, it has the potential to save lives
0
0
196
2w
Update on activity rings
Hello everyone, I am not a developer, just someone with some ideas. my first thought is regarding activity rings- stand, move, exercise. In the current heatwave, health advise on how we do these things changes, meaning the way we complete them may be different or we might not be able to complete them at all. This could de motivate people. is there a way to link them to uk weather alerts or outside temperature so that they complete differently in a heat alert? could they link to a drink water alert?
0
0
178
2w
HKWorkoutBuilder.finishWorkout intermittently returns nil workout and nil error while samples are successfully saved (iOS 26.4–27)
We're seeing an intermittent issue with HKWorkoutBuilder.finishWorkout() in our production app. Our workflow is: builder.beginCollection(withStart: start) { success, error in guard success else { return } let authorizedSamples = samples.filter { self.healthStore.authorizationStatus(for: $0.quantityType) == .sharingAuthorized } builder.add(authorizedSamples) { success, error in guard success else { return } builder.endCollection(withEnd: end) { success, error in guard success else { return } builder.finishWorkout { workout, error in print("workout = \(String(describing: workout))") print("error = \(String(describing: error))") } } } } The logs from affected users are: workout builder begin: result: true, error: nil authorized samples: - HKQuantityTypeIdentifierActiveEnergyBurned - HKQuantityTypeIdentifierDistanceWalkingRunning - HKQuantityTypeIdentifierStepCount workout builder add samples: result: true, error: nil workout builder end: result: true, error: nil workout builder finish: workout: nil, error: nil Result The quantity samples (active energy, distance, step count, etc.) are successfully written to Apple Health. However, no HKWorkout is created. Querying HealthKit immediately afterward also confirms that no HKWorkout exists for the corresponding time range. As a result: The workout does not appear in the Fitness app. It does not contribute to Activity Rings. The quantity samples are visible, but there is no associated workout. Environment We've received reports from multiple users on: iOS 26.4 iOS 26.5 iOS 26.6 iOS 27 beta The issue only affects a small percentage of users. The vast majority complete successfully using exactly the same code path. Things we've verified We've ruled out several common causes: The app is in the foreground (UIApplication.shared.applicationState == .active). The device is unlocked. All HealthKit write permissions have been granted. finishWorkout() is called immediately after endCollection() completes. The quantity samples are successfully saved. Querying HealthKit afterward confirms that the HKWorkout itself was never created. This appears to be different from the documented "device locked" behavior, since the device is unlocked and active when the issue occurs. We also found a related discussion: https://developer.apple.com/forums/thread/825838 In that thread, the issue seems to be related to a locked device. However, our issue also occurs while the device is unlocked and the app remains active. Has anyone experienced similar behavior? Have you found any workaround? Has Apple provided any update through Feedback Assistant or DTS? Has anyone successfully recovered from this state by retrying finishWorkout() or using another approach? We're happy to provide additional logs or a minimal reproducible example if that would be helpful.
0
0
204
2w
Custom Exported Workout missing workoutPlan identifier / Metadata only on the very first app launch/install
Hello everyone, I am experiencing a strange issue regarding retrieving a custom tracking identifier (workoutPlan identifier) from a custom exported workout that has been imported via HealthKit. The Issue: First Fresh Install: When the app is installed for the first time and initialized, it fails to load/fetch the workout plan ID from the imported workout. Subsequent Launches / Re-installs: If I close and relaunch the app, the app successfully fetches the workout plan ID from HealthKit with absolutely no problems. Has anyone found a clean way to handle this without forcing a manual user refresh or an awkward delay/retry mechanism on the first launch? Any insight, workarounds, or best practices would be greatly appreciated! Environment: iOS 17+, Swift, HealthKit
3
0
302
2w
Custom Exported Workout missing workoutPlan identifier / Metadata only on the very first app launch/install
Hello everyone, I am experiencing a strange issue regarding retrieving a custom tracking identifier (workoutPlan identifier) from a custom exported workout that has been imported via HealthKit. The Issue: First Fresh Install: When the app is installed for the first time and initialized, it fails to load/fetch the workout plan ID from the imported workout. Subsequent Launches / Re-installs: If I close and relaunch the app, the app successfully fetches the workout plan ID from HealthKit with absolutely no problems. Has anyone found a clean way to handle this without forcing a manual user refresh or an awkward delay/retry mechanism on the first launch? Any insight, workarounds, or best practices would be greatly appreciated! Environment: iOS 17+, Swift, HealthKit
1
0
217
2w
Workout route map shows incorrect GPS positions in mainland China (iOS 27 beta 3)
I'm a user in mainland China. I use the built-in Workout app on my Apple Watch Series 11 (watchOS 27 beta 3) to record outdoor and indoor workouts, and then view the workout data in the built-in Fitness app on my iPhone Air (iOS 27 beta 3). I've noticed that the marker points on the route map are offset — they deviate from the actual location by several hundred meters, ending up in the middle of a river. Note: This looks like a GCJ-02 coordinate conversion issue. In mainland China, map providers are required to use the GCJ-02 datum, and GPS (WGS-84) coordinates must be converted before being displayed on the map. The offset pattern (several hundred meters) is consistent with WGS-84 coordinates being rendered on a GCJ-02 map without conversion, or a double conversion. I've filed this via Feedback Assistant: FB23716158. Happy to provide a sysdiagnose or sample workout data if needed
1
0
245
2w
Apple Watch awards missing after iPhone iCloud restore
Hello forum-community I hope you're all doing well. My Iphone recently went to apple in order to fix an issue with my camera. After I received it back, I loaded a Backup from ICloud I made before the Iphone went to Apple. So far so good. The Back Up took very long to load onto the device. Especially the apps downloading took almost four hours but I was also fine with that. When the BackUp was finished I had some bugs in some apps like yazio. Some scaling issue led to the app zooming in and out every time I tried to open Yazio. Not really a big deal but it somehow it annoyed me, so I upgraded the Ios from stable 26.5.1 to public beta 26.6 . Enough context. Now my problem: There must have went something wrong while loading the backup. All my workouts from 2023-today, all monthly medals, all other fitness data can be seen in the app. Most medals in the category „workouts“ somehow did NOT sync properly so it looks like I never completed a workout at all. What I've tried so far: Restored both my iPhone and Apple Watch from backups. Verified that all workout history is present (workouts since 2023 are intact). Verified that monthly challenges are still present. Verified that Health data appears complete and correct. Verified that activity data (Move, Exercise, Stand) is present. Confirmed that workout records are correctly stored in the Fitness and Health apps. Updated the iPhone to the latest iOS beta version. Unpaired and re-paired the Apple Watch. Restored the Apple Watch from an older backup. Allowed several days (approximately 5+ days) for Fitness and Health data to resynchronize. Kept both devices connected to Wi-Fi and charging for extended periods. Confirmed that some achievements (e.g. Longest Move Streak) are displayed correctly. Confirmed that many Workout Awards are missing or shown as not earned. Confirmed that some “Close Your Rings” awards are incorrect or missing. Confirmed that awards for workouts already completed after the restore (e.g. Walking Workout, Running Workout) remain greyed out. Confirmed that newly completed qualifying workouts are recorded correctly but do not trigger the corresponding awards. Verified that the issue persists after restoring the Apple Watch from a different backup. Contacted Apple Support. Apple Support declined further troubleshooting because the iPhone is running a beta version of iOS and recommended restoring to a non-beta version (already did that - result: no fitness data at all) Any more suggestions on how to fix this? Thanks everybody!
1
1
448
3w
Unable to invalidate interval: no data source available error when fetching steps using HKStatisticsCollectionQuery
While attempting to read a user’s daily step history spanning backward to the last 7 days, a small but consistent subset of users encounter Error Code 3 with the underlying error description: Error Code 3 "Unable to invalidate interval: no data source available." When this error occurs, we are entirely unable to read their step history. We have received ~10 direct user reports of this within the last couple of weeks.
14
2
1.5k
4w
Feature Proposal: Apple Intelligence Guided Workouts for Apple Watch
Hi everyone, After watching WWDC26 and going for a run today, I came up with an idea that I believe could be a natural extension of Apple Intelligence and Apple Watch. This proposal is not intended to replace Custom Workouts. Instead, it focuses on removing the manual setup required to create them by allowing Apple Intelligence to understand workout plans written in natural language. Today, Apple Watch already supports Custom Workouts, but users still have to manually recreate interval workouts. For example: • Walk 5 minutes • Run 1 minute • Walk 1 minute 30 seconds • Repeat 6 times Instead, Apple Intelligence could understand workouts written in natural language and automatically generate a structured Apple Watch workout. This could work from multiple sources: Notes Messages Mail PDFs Screenshots Photos of printed training plans Websites The generated workout could then be reviewed by the user before being saved and synchronized to Apple Watch. Intelligent Haptics I also imagined an optional feature called Intelligent Haptics. Instead of using a single vibration for interval transitions, the watch could communicate through different haptic patterns: Progressive vibration before a running interval starts. Decreasing vibration when an interval ends. Rhythmic vibrations during recovery to help regulate breathing. The goal isn't simply to notify the user—it is to reduce the need to constantly look at the display and allow them to stay focused on the workout. Since Apple Intelligence is becoming a system-wide capability, I think workouts could be understood just like calendar events, reminders or emails. I have already submitted this proposal through Feedback Assistant, but I would love to hear what other developers think. Would this be a feature you would like to see in watchOS? I'm curious to hear how other developers would improve this concept.
0
0
393
Jul ’26
watchOS: Is there a public API to initiate an HRV measurement?
I'm developing a watchOS meditation app in which the user starts one continuous meditation session. During that session, I'd like the app to obtain a 1-minute HRV measurement immediately after the session begins (to establish a baseline), and then automatically obtain another 1-minute HRV measurement approximately 6 minutes after the session started, without requiring the user to manually start a second measurement or leave the app. My understanding is that HealthKit allows apps to read HRV samples after they have been recorded, but I haven't found a way to request that the watch generate a new HRV measurement. Is there any public API that allows a third-party watchOS app to initiate an HRV measurement similar to the Mindfulness/Breathe app, or otherwise request the Apple Watch to collect a new HRV sample at predetermined times during an ongoing session? Thanks in advance, Hern
Replies
0
Boosts
0
Views
87
Activity
5d
Accuracy of IBI Values Measured by Apple Watch
I am currently developing an app that measures HRV to estimate stress levels. To align the values more closely with those from Galaxy devices, I decided not to use the heartRateVariabilitySDNN value provided by HealthKit. Instead, I extracted individual interbeat intervals (IBI) using the HKHeartBeatSeries data. Can I obtain accurate IBI data using this method? If not, I would like to know how I can retrieve more precise data. Any insights or suggestions would be greatly appreciated. Here is a sample code I tried. @Observable class HealthKitManager: ObservableObject { let healthStore = HKHealthStore() var ibiValues: [Double] = [] var isAuthorized = false func requestAuthorization() { let types = Set([ HKSeriesType.heartbeat(), HKQuantityType.quantityType(forIdentifier: .heartRateVariabilitySDNN)!, ]) healthStore.requestAuthorization(toShare: nil, read: types) { success, error in DispatchQueue.main.async { self.isAuthorized = success if success { self.fetchIBIData() } } } } func fetchIBIData() { var timePoints: [TimeInterval] = [] var absoluteStartTime: Date? let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(identifier: "Asia/Seoul") dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" var calendar = Calendar.current calendar.timeZone = TimeZone(identifier: "Asia/Seoul") ?? .current var components = DateComponents() components.year = 2025 components.month = 4 components.day = 3 components.hour = 15 components.minute = 52 components.second = 0 let startTime = calendar.date(from: components)! components.hour = 16 components.minute = 0 let endTime = calendar.date(from: components)! let predicate = HKQuery.predicateForSamples(withStart: startTime, end: endTime, options: .strictStartDate) let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false) let query = HKSampleQuery(sampleType: HKSeriesType.heartbeat(), predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sortDescriptor]) { (_, samples, _) in if let sample = samples?.first as? HKHeartbeatSeriesSample { absoluteStartTime = sample.startDate let startDateKST = dateFormatter.string(from: sample.startDate) let endDateKST = dateFormatter.string(from: sample.endDate) print("series start(KST):\(startDateKST)\tend(KST):\(endDateKST)") let seriesQuery = HKHeartbeatSeriesQuery(heartbeatSeries: sample) { query, timeSinceSeriesStart, precededByGap, done, error in if !precededByGap { timePoints.append(timeSinceSeriesStart) } if done { for i in 1..<timePoints.count { let ibi = (timePoints[i] - timePoints[i-1]) * 1000 // Convert to milliseconds // Calculate absolute time for current beat if let startTime = absoluteStartTime { let beatTime = startTime.addingTimeInterval(timePoints[i]) let beatTimeString = dateFormatter.string(from: beatTime) print("IBI: \(String(format: "%.2f", ibi)) ms at \(beatTimeString)") } self.ibiValues.append(ibi) } } } self.healthStore.execute(seriesQuery) } else { print("No samples found for the specified time range") } } self.healthStore.execute(query) } }
Replies
3
Boosts
0
Views
247
Activity
1w
HealthKit Time in Daylight: sample granularity, latency, and relationship to Health app values
Hi, We are integrating HKQuantityTypeIdentifierTimeInDaylight into a research application and have a few questions about how developers should interpret the data returned by HealthKit. Specifically: Should TimeInDaylight samples be treated as having a fixed minimum temporal granularity (for example, approximately 5-minute intervals), or is the sample duration implementation-dependent and subject to change? Is there any expected latency between a daylight exposure event and the corresponding TimeInDaylight sample becoming available through HealthKit? For example, are samples intended to appear shortly after exposure, or only after periodic processing and synchronization? In the Health app, each Time in Daylight sample displays a Maximum Light Intensity (lux). Is this value available through the public HealthKit API (e.g., metadata), or is it only used internally by the Health app? More generally, should developers consider TimeInDaylight to be a high-level derived metric rather than expecting a direct correspondence with underlying ambient light sensor observations? Thank you.
Replies
0
Boosts
0
Views
133
Activity
1w
technical clarification on sensorkit measurement sampling
Dear SensorKit team, We are currently working with SensorKit ambient light data under our approved SensorKit entitlement for research use. We would be grateful for some technical clarification on the sampling strategy for the SRSensor.ambientLightSensor stream, as this directly affects how we analyse and report the data. In exported data from Apple Watch, we observe that ambient light samples do not appear to follow a fixed sampling cadence. Instead, the data appear burst-like: in one short window, we see many samples with inter-sample intervals around 100 ms, occasional near-duplicate timestamps, and then gaps of around 10 to 30 seconds with no samples. This suggests that the stream may be adaptive, event-triggered, buffered, or subject to system-level sampling decisions. We also noticed a related discrepancy when comparing the SensorKit ambient light trace with the Health app display for a corresponding Time in Daylight sample. In one example, the Health app shows a 5-minute Time in Daylight interval with a “Maximum Light Intensity” value of 9,493 lux. In the SensorKit ambient light trace around that period, the raw samples show a different maximum depending on the precise time window considered, including higher values shortly before the HealthKit interval start and lower values within the subset of SensorKit samples we inspected. We realise that Time in Daylight may be generated by a separate internal aggregation or classification pipeline, but this comparison raised the question of how closely SensorKit ambient light samples should be expected to correspond to the light intensity values displayed in Health. Could you clarify the following points for SensorKit ambient light data? Is SRSensor.ambientLightSensor sampled at a fixed cadence, or is sampling adaptive / event-driven? If sampling is adaptive, what factors influence sampling density? For example, changes in illuminance, device or wrist motion, device orientation, display state, app state, power state, charging state, or other system-level conditions. Are ambient light readings buffered and delivered or exported in bursts? Do SensorKit timestamps correspond to the physical sensor acquisition time, processing time, or the time at which the sample is made available through SensorKit? Are duplicate or near-duplicate ambient light samples expected in SensorKit exports? Are there circumstances under which ambient light sampling is suspended, downsampled, or suppressed? Is SensorKit ambient light expected to match, approximate, or differ from the light intensity values shown in Health app Time in Daylight sample details? Is the “Maximum Light Intensity” shown for Time in Daylight computed from the same underlying ambient light sensor stream exposed through SensorKit, or from a separate internal stream or aggregation? Are there recommended practices for analysing SensorKit ambient light data, especially with respect to irregular sampling, burst sampling, missing intervals, and aggregation to longer time windows? Is the sampling strategy the same across Apple Watch hardware versions, or should researchers expect device-specific differences? We do not need proprietary implementation details. Our goal is to understand the methodological constraints well enough to analyse the data appropriately and describe the limitations accurately in scientific work. Thank you!
Replies
2
Boosts
0
Views
339
Activity
1w
HKWorkoutBuilder.finishWorkout() fails silently (nil workout, nil error) when device is locked (iOS 26.4+)
Hello everyone, We are encountering a critical regression introduced in iOS 26.4 that results in permanent workout data loss for users. When invoking HKWorkoutBuilder.finishWorkout(completion:) while the iOS device is locked, the save operation fails completely. However, it fails silently: the completion handler executes but returns both a nil workout and a nil error. Expected Behavior: Before iOS 26.4 finishWorkout resulted in a workout id, and correctly stored the workout data in HealthKit. According to HealthKit data protection documentation, saving data when the device is locked should either succeed (writing to a temporary journal file to be merged upon unlock) or explicitly throw an error such as HKError.Code.errorDatabaseInaccessible. Actual Behavior: Because the framework returns nil for both the object and the error, the application has no way to detect that the save failed. We cannot implement a retry mechanism or queue the save, resulting in silent data loss. Steps to Reproduce: We have built a Minimal Reproducible Example (MRE) that reliably triggers this: Initialize an HKWorkoutBuilder and call beginCollection(withStart:) followed by endCollection(withEnd:). Wrap the finishWorkout call in a short 5-second asynchronous delay, protected by a UIBackgroundTask to prevent app suspension. Lock the physical device during this 5-second window. The finishWorkout completion handler will execute while the device is locked, returning workout == nil and error == nil. Existing Reports: We have filed this via Feedback Assistant (a month ago) and opened a TSI (a week ago), providing the MRE project and a sysdiagnose captured at the time of failure: Feedback ID: FB22396180 TSI Case-ID: 19755043 As we have not yet received a response or a suggested workaround through these official channels, we are reaching out to the community. Has anyone else encountered this silent failure with HKWorkoutBuilder recently? Any insights or escalation help would be greatly appreciated.
Replies
6
Boosts
2
Views
773
Activity
1w
Please add Sleep Tracking support for Family Setup Apple Watches
Hi everyone, I’d love to see Apple add full Sleep Tracking support for Apple Watches that are set up using Family Setup. Many families use Family Setup for children or older family members who don’t have an iPhone of their own. Sleep is one of the most important health metrics, and it would be incredibly useful if caregivers could view sleep duration and trends just like they can with other health features. This would help parents better understand their child’s sleep habits and would also be valuable for families caring for older adults. Even if detailed health data stayed private, allowing sleep summaries to sync through Family Setup would make the feature much more useful. I hope Apple considers adding this in a future watchOS update. Is this something anyone else would find helpful?
Replies
0
Boosts
0
Views
148
Activity
1w
Apple watch and phone communication / data transfer keeps failing
I'm building a tennis App, but I noticed the data update between the phone and watch keeps failing if I placed my camera on the baseline and player is moving around on the court. I'm trying to notify the player when they did something wrong when the camera detected it in realtime. I'm using HKWorkoutSession to keep the watch alive. Any suggestion?
Replies
0
Boosts
0
Views
158
Activity
2w
HKStatisticsCollectionQueryDescriptor intermittently returns no data for certain date ranges on iOS 27
We are seeing inconsistent results from HKStatisticsCollectionQueryDescriptor on iOS 27. Using the same quantity type, statistics options, anchor date, interval components, and predicate configuration, some date ranges return the expected statistics, while other ranges unexpectedly return empty results or buckets with no quantity. The affected ranges do contain HealthKit samples: HKSampleQueryDescriptor finds samples in the same date range. HKStatisticsQueryDescriptor returns the expected value when run separately for an affected bucket. HKStatisticsCollectionQueryDescriptor returns no quantity for that same bucket. Slightly expanding or shifting the date range may cause the collection query to return data again. A simplified version of the query looks like this: let datePredicate = HKQuery.predicateForSamples( withStart: startDate, end: endDate, options: .strictStartDate ) let descriptor = HKStatisticsCollectionQueryDescriptor( predicate: .quantitySample( type: quantityType, predicate: datePredicate ), options: .cumulativeSum, anchorDate: anchorDate, intervalComponents: DateComponents(day: 1) ) let collection = try await descriptor.result(for: healthStore) collection.enumerateStatistics(from: startDate, to: endDate) { statistics, _ in let quantity = statistics.sumQuantity() print(statistics.startDate, quantity as Any) } Expected behavior Every interval containing matching samples should return the corresponding statistics, regardless of the overall requested date range. Actual behavior Some date ranges produce missing or empty buckets even though matching samples exist and an individual HKStatisticsQueryDescriptor can calculate the expected value. Changing only the date range can make the data appear or disappear. The samples are visible to the app in the affected range, so this does not appear to be explained solely by iOS 27’s Limited History authorization. This behavior was not observed with the same query flow on earlier iOS versions. Is this a known regression in HKStatisticsCollectionQueryDescriptor on iOS 27, or has the expected date-range or predicate behavior changed?
Replies
0
Boosts
0
Views
204
Activity
2w
Track workouts with HealthKit on iOS + GPS tracking
I've built an iOS app according to this WWDC25 video (https://developer.apple.com/videos/play/wwdc2025/322). I added GPS tracking for workouts. In Xcode, I've enabled Signing & Capabilities > Background Modes: Location Updates. And in my code, I request CLAuthorisationStatus.authorizedAlways. Everything works as expected, but I am unsure if .authorizedWhenInUse will not be sufficient for this kind of app. It seems even to work when I use .authorizedWhenInUse as either the Dynamic Island or the Live Activity is shown when the app is not in the foreground. I need clarification by an expert.
Replies
1
Boosts
0
Views
576
Activity
2w
National early warning system for sepsis
this may be too hard to achieve at the moment. sepsis can develop very quickly News2 is an app available on the store that measures the components of sepsis - pulse rate, blood pressure,respiratory rate, oxygen levels, temperature and conscious level - new confusion, it was developed by the royal college of physicians. some of these things can be measured on an Apple Watch. I am not a doctor, but I wonder if it would be possible to develop something for a watch that would prompt the wearing to think about it or even ask are you ok and manage in a similar way to it looks like you have had a fall. it might mean the wearer adding more information into Apple health, for instance whether they have Copd, use oxygen etc, so the system has a baseline jus a thought, and the rcp would be the best people to contact regarding the efficacy of this, but if it could be added, it has the potential to save lives
Replies
0
Boosts
0
Views
196
Activity
2w
Update on activity rings
Hello everyone, I am not a developer, just someone with some ideas. my first thought is regarding activity rings- stand, move, exercise. In the current heatwave, health advise on how we do these things changes, meaning the way we complete them may be different or we might not be able to complete them at all. This could de motivate people. is there a way to link them to uk weather alerts or outside temperature so that they complete differently in a heat alert? could they link to a drink water alert?
Replies
0
Boosts
0
Views
178
Activity
2w
HKWorkoutBuilder.finishWorkout intermittently returns nil workout and nil error while samples are successfully saved (iOS 26.4–27)
We're seeing an intermittent issue with HKWorkoutBuilder.finishWorkout() in our production app. Our workflow is: builder.beginCollection(withStart: start) { success, error in guard success else { return } let authorizedSamples = samples.filter { self.healthStore.authorizationStatus(for: $0.quantityType) == .sharingAuthorized } builder.add(authorizedSamples) { success, error in guard success else { return } builder.endCollection(withEnd: end) { success, error in guard success else { return } builder.finishWorkout { workout, error in print("workout = \(String(describing: workout))") print("error = \(String(describing: error))") } } } } The logs from affected users are: workout builder begin: result: true, error: nil authorized samples: - HKQuantityTypeIdentifierActiveEnergyBurned - HKQuantityTypeIdentifierDistanceWalkingRunning - HKQuantityTypeIdentifierStepCount workout builder add samples: result: true, error: nil workout builder end: result: true, error: nil workout builder finish: workout: nil, error: nil Result The quantity samples (active energy, distance, step count, etc.) are successfully written to Apple Health. However, no HKWorkout is created. Querying HealthKit immediately afterward also confirms that no HKWorkout exists for the corresponding time range. As a result: The workout does not appear in the Fitness app. It does not contribute to Activity Rings. The quantity samples are visible, but there is no associated workout. Environment We've received reports from multiple users on: iOS 26.4 iOS 26.5 iOS 26.6 iOS 27 beta The issue only affects a small percentage of users. The vast majority complete successfully using exactly the same code path. Things we've verified We've ruled out several common causes: The app is in the foreground (UIApplication.shared.applicationState == .active). The device is unlocked. All HealthKit write permissions have been granted. finishWorkout() is called immediately after endCollection() completes. The quantity samples are successfully saved. Querying HealthKit afterward confirms that the HKWorkout itself was never created. This appears to be different from the documented "device locked" behavior, since the device is unlocked and active when the issue occurs. We also found a related discussion: https://developer.apple.com/forums/thread/825838 In that thread, the issue seems to be related to a locked device. However, our issue also occurs while the device is unlocked and the app remains active. Has anyone experienced similar behavior? Have you found any workaround? Has Apple provided any update through Feedback Assistant or DTS? Has anyone successfully recovered from this state by retrying finishWorkout() or using another approach? We're happy to provide additional logs or a minimal reproducible example if that would be helpful.
Replies
0
Boosts
0
Views
204
Activity
2w
Apple Health not connecting Blood Pressure from OMRON App
iOS 27 beta 3 broke my Apple health and blood pressure monitor and according to omron app, everything is being sent to Apple health. All permissions given. But blood pressure will not transfer into health.
Replies
1
Boosts
0
Views
248
Activity
2w
Custom Exported Workout missing workoutPlan identifier / Metadata only on the very first app launch/install
Hello everyone, I am experiencing a strange issue regarding retrieving a custom tracking identifier (workoutPlan identifier) from a custom exported workout that has been imported via HealthKit. The Issue: First Fresh Install: When the app is installed for the first time and initialized, it fails to load/fetch the workout plan ID from the imported workout. Subsequent Launches / Re-installs: If I close and relaunch the app, the app successfully fetches the workout plan ID from HealthKit with absolutely no problems. Has anyone found a clean way to handle this without forcing a manual user refresh or an awkward delay/retry mechanism on the first launch? Any insight, workarounds, or best practices would be greatly appreciated! Environment: iOS 17+, Swift, HealthKit
Replies
3
Boosts
0
Views
302
Activity
2w
Custom Exported Workout missing workoutPlan identifier / Metadata only on the very first app launch/install
Hello everyone, I am experiencing a strange issue regarding retrieving a custom tracking identifier (workoutPlan identifier) from a custom exported workout that has been imported via HealthKit. The Issue: First Fresh Install: When the app is installed for the first time and initialized, it fails to load/fetch the workout plan ID from the imported workout. Subsequent Launches / Re-installs: If I close and relaunch the app, the app successfully fetches the workout plan ID from HealthKit with absolutely no problems. Has anyone found a clean way to handle this without forcing a manual user refresh or an awkward delay/retry mechanism on the first launch? Any insight, workarounds, or best practices would be greatly appreciated! Environment: iOS 17+, Swift, HealthKit
Replies
1
Boosts
0
Views
217
Activity
2w
Workout route map shows incorrect GPS positions in mainland China (iOS 27 beta 3)
I'm a user in mainland China. I use the built-in Workout app on my Apple Watch Series 11 (watchOS 27 beta 3) to record outdoor and indoor workouts, and then view the workout data in the built-in Fitness app on my iPhone Air (iOS 27 beta 3). I've noticed that the marker points on the route map are offset — they deviate from the actual location by several hundred meters, ending up in the middle of a river. Note: This looks like a GCJ-02 coordinate conversion issue. In mainland China, map providers are required to use the GCJ-02 datum, and GPS (WGS-84) coordinates must be converted before being displayed on the map. The offset pattern (several hundred meters) is consistent with WGS-84 coordinates being rendered on a GCJ-02 map without conversion, or a double conversion. I've filed this via Feedback Assistant: FB23716158. Happy to provide a sysdiagnose or sample workout data if needed
Replies
1
Boosts
0
Views
245
Activity
2w
Dive workout
Hello, How can I read the dive count and total underwater time for a Dive workout from Apple Health? Is this information available through HealthKit, and if so, which APIs or workout metadata keys should I use? Thanks! Stéphane
Replies
2
Boosts
0
Views
345
Activity
3w
Apple Watch awards missing after iPhone iCloud restore
Hello forum-community I hope you're all doing well. My Iphone recently went to apple in order to fix an issue with my camera. After I received it back, I loaded a Backup from ICloud I made before the Iphone went to Apple. So far so good. The Back Up took very long to load onto the device. Especially the apps downloading took almost four hours but I was also fine with that. When the BackUp was finished I had some bugs in some apps like yazio. Some scaling issue led to the app zooming in and out every time I tried to open Yazio. Not really a big deal but it somehow it annoyed me, so I upgraded the Ios from stable 26.5.1 to public beta 26.6 . Enough context. Now my problem: There must have went something wrong while loading the backup. All my workouts from 2023-today, all monthly medals, all other fitness data can be seen in the app. Most medals in the category „workouts“ somehow did NOT sync properly so it looks like I never completed a workout at all. What I've tried so far: Restored both my iPhone and Apple Watch from backups. Verified that all workout history is present (workouts since 2023 are intact). Verified that monthly challenges are still present. Verified that Health data appears complete and correct. Verified that activity data (Move, Exercise, Stand) is present. Confirmed that workout records are correctly stored in the Fitness and Health apps. Updated the iPhone to the latest iOS beta version. Unpaired and re-paired the Apple Watch. Restored the Apple Watch from an older backup. Allowed several days (approximately 5+ days) for Fitness and Health data to resynchronize. Kept both devices connected to Wi-Fi and charging for extended periods. Confirmed that some achievements (e.g. Longest Move Streak) are displayed correctly. Confirmed that many Workout Awards are missing or shown as not earned. Confirmed that some “Close Your Rings” awards are incorrect or missing. Confirmed that awards for workouts already completed after the restore (e.g. Walking Workout, Running Workout) remain greyed out. Confirmed that newly completed qualifying workouts are recorded correctly but do not trigger the corresponding awards. Verified that the issue persists after restoring the Apple Watch from a different backup. Contacted Apple Support. Apple Support declined further troubleshooting because the iPhone is running a beta version of iOS and recommended restoring to a non-beta version (already did that - result: no fitness data at all) Any more suggestions on how to fix this? Thanks everybody!
Replies
1
Boosts
1
Views
448
Activity
3w
Unable to invalidate interval: no data source available error when fetching steps using HKStatisticsCollectionQuery
While attempting to read a user’s daily step history spanning backward to the last 7 days, a small but consistent subset of users encounter Error Code 3 with the underlying error description: Error Code 3 "Unable to invalidate interval: no data source available." When this error occurs, we are entirely unable to read their step history. We have received ~10 direct user reports of this within the last couple of weeks.
Replies
14
Boosts
2
Views
1.5k
Activity
4w
Feature Proposal: Apple Intelligence Guided Workouts for Apple Watch
Hi everyone, After watching WWDC26 and going for a run today, I came up with an idea that I believe could be a natural extension of Apple Intelligence and Apple Watch. This proposal is not intended to replace Custom Workouts. Instead, it focuses on removing the manual setup required to create them by allowing Apple Intelligence to understand workout plans written in natural language. Today, Apple Watch already supports Custom Workouts, but users still have to manually recreate interval workouts. For example: • Walk 5 minutes • Run 1 minute • Walk 1 minute 30 seconds • Repeat 6 times Instead, Apple Intelligence could understand workouts written in natural language and automatically generate a structured Apple Watch workout. This could work from multiple sources: Notes Messages Mail PDFs Screenshots Photos of printed training plans Websites The generated workout could then be reviewed by the user before being saved and synchronized to Apple Watch. Intelligent Haptics I also imagined an optional feature called Intelligent Haptics. Instead of using a single vibration for interval transitions, the watch could communicate through different haptic patterns: Progressive vibration before a running interval starts. Decreasing vibration when an interval ends. Rhythmic vibrations during recovery to help regulate breathing. The goal isn't simply to notify the user—it is to reduce the need to constantly look at the display and allow them to stay focused on the workout. Since Apple Intelligence is becoming a system-wide capability, I think workouts could be understood just like calendar events, reminders or emails. I have already submitted this proposal through Feedback Assistant, but I would love to hear what other developers think. Would this be a feature you would like to see in watchOS? I'm curious to hear how other developers would improve this concept.
Replies
0
Boosts
0
Views
393
Activity
Jul ’26