HealthKit

RSS for tag

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

HealthKit Documentation

Posts under HealthKit tag

106 Posts
Sort by:
Post not yet marked as solved
2 Replies
86 Views
Our watchOS app uses CMFallDetectionManager (with the proper entitlement) to help alert our users and their caregivers when a fall occurs. We have had a simple implementation in our app for a couple of years now and it seems to work fine. Recently, we received a report of delayed fall alerts and have traced back the root cause to a failure from the system to call func fallDetectionManager(_ fallDetectionManager: CMFallDetectionManager, didDetect event: CMFallDetectionEvent, completionHandler handler: @escaping () -> Void) promptly when a fall occurs. Our implementation of this method begins with the following logging statement: "Fall detected at \(event.date) with status \(event.resolution.rawValue) at \(Date())" When we check our logs, we see a number of events that occur as expected, for example: Fall detected at DATE_AND_HOURS:42:09 +0000 with status 1 at DATE_AND_HOURS:42:51 +0000 However, many events show a period of several minutes from fall detection to a report: Fall detected at DATE_AND_HOURS:28:09 +0000 with status 0 at DATE_AND_HOURS:32:42 +0000 or Fall detected at DATE_AND_HOURS:44:26 +0000 with status 1 at DATE_AND_HOURS:48:14 +0000 And in the instance from our customer, we had a fall detected that evidently wasn't reported for 5 hours and 4 minutes (I'm not sharing exact timestamps publicly to maintain user privacy). We are aware of the documentation regarding the delegate and have programmed it appropriately not to receive duplicate events: Additionally, each time the user launches your app, the system checks to see if a fall event has occurred during the recent past. If one has occurred, it calls this method. Note that your app may receive the same event multiple times, for example, if the app crashes and relaunches. Always check the event’s date property to determine whether your app has already received the event. The system guarantees that different fall events have different date values. Moreover, our logger persists logs when there is no network access, and the delegate callback also requests a network post to our servers that, again, is preserved in a background queue until connectivity is restored if it's not available. Our app's other updates (watchOS complication, etc.) from this user's Watch also show that our app was running in the background and communicating with our servers during that time. We have very high confidence that the watch and our app did not miss any more timely calls to that delegate method. While this one five-hour delay was an exceptionally bad occurrence, we also find the other delays of several minutes to be concerning, considering the time-sensitive nature of falls. Does Apple or do any developers have any insights about what's going on and what expectations we should be setting for our users?
Posted
by bcappdev.
Last updated
.
Post not yet marked as solved
1 Replies
69 Views
Hello, I’m currently developing a fitness app for watchOS that lets a user to manually set a desired heart rate target zone (enter numbers representing the lower and upper boundaries) and start a workout (right now it’s only “Other” type). After that my app monitors user’s heart rate and alerts them when they’re out of zone. When user ends the workout, the info about this workout appears on “Fitness” iOS app, and user can see the workout data like Workout Time, Active and Total Calories, Avg. Heart Rate. Also user can see Heart Rate chart with info how their heart rate was changing during a workout (see the Figure 1). Now to the question. When user clicks “Show More” button above the Heart Rate chart, they can see the same Heart Rate chart and another one, with Post-Workout Heart Rate (see the Figure 2). But there is no “Estimated time in each heart rate zone” as one can see in the workout’s details that were recorded from Apple’s workout (watchOS “Workout” app, for a workout of “Other” type as well). Please see the Figure 3. The question is: is it possible to add “Estimated time in each heart rate zone” to workout recorded via my third-party app so it would look like on the Figure 3 in "Fitness" iOS app, and if it's possible, what steps should I undertake to implement this ? Thanks in advance! I posted the screenshots in the replies to the post, because otherwise I was not able to submit a post ("sensitive language" warning, I suspect it's because of the ids in the attached screenshot's urls)
Posted Last updated
.
Post not yet marked as solved
0 Replies
92 Views
Hello, I am writing as I am seeing a very strange behavior when attempting to run an HKStatisticsCollectionQuery over multiple app starts. Steps: Initially load and launch my app into an iOS simulator (running iOS 17.2) via Xcode (version 15.3). Execute code path which invokes the following method below. Authorize necessary Read permission for the HKQuantityTypeIdentifierStepCount type. Observed that a non-nil HKStatisticsCollection is returned in the initialResultsHandler, with corresponding expected datapoints. These datapoints are in no way stored or retained on the device at all. Stop the app via Xcode. Relaunch the app via Xcode. Execute the same code path as in step 2. Observed (via breakpoints) that even though the query is executed by the HKHealthStore, the initialResultsHandler is never called and no HKStatisticsCollection is ever returned. Input parameters are the same in both instances of the call, and can confirm there is data in the devices HealthKit datastore. I would expect, reading Apple's documentation, that both queries should execute and return the exact same datapoints in an HKStatisticsCollection, but please feel free to correct me if I am misunderstanding something, or if my code is incorrect in some way. func fetchStatisticsCollection(with quantityType: HKQuantityType, predicate: NSPredicate? = nil, options: HKStatisticsOptions, anchorDate: Date? = nil, interval: DateComponents? = nil, initialResultsCompletion: @escaping (Result<HKStatisticsCollection, Error>) -> Void, updateHandler: (Result<HKStatisticsCollection, Error>) -> Void?) { var statisticsQueryAnchorDate: Date = Date() if let anchor = anchorDate { statisticsQueryAnchorDate = anchor } else if let yesterdayAnchor = createStaticsQueryAnchorDateYesterday(){ statisticsQueryAnchorDate = yesterdayAnchor } let dateInterval = interval ?? DateComponents(day: 1) // Create the query let query = HKStatisticsCollectionQuery(quantityType: quantityType, quantitySamplePredicate: predicate, options: options, anchorDate: statisticsQueryAnchorDate, intervalComponents: dateInterval) // Set the results handler query.initialResultsHandler = { query, results, error in if let error = error as? HKError{ // Return wrapped HKError initialResultsCompletion(.failure(HealthKitManagerError.hkError(error: error))) return } guard let statsCollection = results else { // Return custom Empty Results error. initialResultsCompletion(.failure(HealthKitManagerError.emptyResults)) return } initialResultsCompletion(.success(statsCollection)) } if let updateHandler = updateHandler { query.statisticsUpdateHandler = { query, statistics, statisticsCollection, error in if let error = error as? HKError{ // Return custom wrapped HKError. updateHandler(.failure(HealthKitManagerError.hkError(error: error))) return } guard let statsCollection = statisticsCollection else { // Return custom Empty Results error. updateHandler(.failure(HealthKitManagerError.emptyResults)) return } updateHandler(.success(statsCollection)) } } if activeTypeQueries[quantityType.identifier] == nil { healthStore.execute(query) activeTypeQueries[quantityType.identifier] = query healthStore.enableBackgroundDelivery(for: quantityType, frequency: .immediate) { (success, error) in if let error = error { return } if success { print("background enabled") } } } else { print("NOT executing query, we already have one query running for this type") } } Thank you
Posted Last updated
.
Post marked as solved
1 Replies
112 Views
Hi All, I have a strange issue. I am using enableBackgroundDelivery for updating user step count in background mode using health kit. It works fine when I execute the app by pressing 'Run' in xcode. But the code is not triggering when I am directly launching it on my device. I have tried many different things but cannot figure out the issue from 2 days 😭. I would really appreciate any suggestions. Thanks
Posted Last updated
.
Post not yet marked as solved
1 Replies
565 Views
I'm using the new watchOS 9 HKWorkoutActivity in my interval training app (Intervals Pro) for each interval. It's a great addition since all the intervals now show in the Apple Fitness app, however, if the workout has lots of activities then saving the workout is painfully slow. For example, on my Apple Watch Ultra I saved a workout with 63 activities and it took more than 1 minute. Here's a code snippet: try await builder.endCollection(at: workoutEndDate) try await builder.addMetadata(metadata) try await builder.finishWorkout() // This is SLOW Is anyone else having the same issue? To demonstrate the issue you can look at a Test Flight build of Intervals Pro: https://testflight.apple.com/join/Nn7iSOzY Tap on the More tab in the iPhone app and then the Apple Watch Settings. On that screen you'll see a switch to either enable or disable workout activities. To demonstrate the issue, edit a timer to continue until manually stopped by changing the Number of Cycles to "Until Stopped". Then start the timer on the watch. Let it run for a period of time to create more than 50 intervals, for example, then stop the timer. Swipe to the leftmost screen on the watch, tap pause, then tap end. At that point you'll see how slow the workout saved. Next, you can go back to the iPhone app, disable using workout activities and repeat the test. The workout will save quickly in this case. I've filed a feedback.
Posted
by jbailey.
Last updated
.
Post not yet marked as solved
0 Replies
139 Views
I noticied that my workout session is sometimes being killed by apple when the app is in the background and it seems that the func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) { is only being called when the app comes back into the foreground. I wonder if there is a way for us to get notified when the workout is about to die or has already been killed. Thanks
Posted Last updated
.
Post marked as Apple Recommended
242 Views
How can I open the user's Health Privacy Settings directly from my app when I'd like them to review them? I believe similar questions have been asked before like this one: https://forums.developer.apple.com/forums/thread/730434 However, I'm wondering if the situation is changed for iOS 17 or if there's a way that works for Health permissions. This is directly possible in the Garmin Connect app for example which is a major app on the store.
Posted Last updated
.
Post not yet marked as solved
0 Replies
256 Views
When I connect a speed and cadence sensor to my Apple Watch in Bluetooth settings I expect to see the following HKQuantity types in workoutBuilder:(HKLiveWorkoutBuilder *)workoutBuilder didCollectDataOfTypes HKQuantityTypeIdentifierCyclingSpeed, HKQuantityTypeIdentifierDistanceCycling, and HKQuantityTypeIdentifierCyclingCadence. However, after starting an HKWorkoutSession I only get updates for HKQuantityTypeIdentifierDistanceCycling. I know that these metrics are being updated because the Apple Workout app displays them. I have authorized my app to read and write these quantity types, so what could I be missing here? Are these quantities only available to the workout app, as I haven't found a third-party app that sees these metrics when the sensors are connected this way?
Posted Last updated
.
Post not yet marked as solved
0 Replies
212 Views
Hello, We are currently developing a healthcare app using React Native and have successfully implemented the feature to fetch data such as step count, weight, blood pressure, and heart rate from HealthKit. While we have no issues with the data retrieval itself, we have encountered a problem regarding the blood pressure data. In HealthKit's Heart → Blood Pressure → Data Sources & Access section, the "APPS AND SERVICES ALLOWED TO READ DATA" shows as "NONE," and there's no option within HealthKit to toggle the connection ON or OFF. Instead, the control for ON/OFF is available in the iPhone's SETTINGS → Health → Data Sources & Access, specifically for "Diastolic Blood Pressure" and "Systolic Blood Pressure". Please note that the ability to toggle ON/OFF within HealthKit is available for step count, weight, and heart rate. Could this issue with blood pressure data be due to the requirement of two permissions (for diastolic and systolic readings), and that's why it's not displayed correctly in HealthKit? What are the possible solutions for controlling the blood pressure data ON/OFF toggle within HealthKit?
Posted
by gskdev.
Last updated
.
Post not yet marked as solved
0 Replies
300 Views
Hey! TLDR: How Health app knows the new menstruation cycle started? The API Adding .menstrualFlow (HKCategoryValueMenstrualFlow) samples require HKMetadataKeyMenstrualCycleStart: Bool parameter. It's fairly simple for the consecutive days - the first sample includes true, the rest false. The problem What about more complex scenarios like: 3 days of unspecified samples, then 2 days of none samples, and unspecified sample again. Should it be marked as the new cycle start? I don't want to prompt the user to confirm the new menstruation cycle. Observations I noticed Health app performs some logic under the hood. For instance, when I marked 5 days in a row unspecified, then left 6 days in a row empty, then selected unspecified again, I got 2 menstruation cycles (11 days ago and today). But when I changed the number of the days I marked as unspecified before the gap, or the length of the gap, or edited the cycles further in the past, I ended up having just 1 menstruation cycle. I guess Health app takes into consideration: previous menstruation length, gap length, average cycle length. But what is the exact math here? I don't want to ruin the user's statistics 💚 I found in the user guide this info about the fertility: The fertile window will be the six days you're most likely to be fertile, based on data that you’ve logged about your period or a positive ovulation test result. The fertile window prediction is based on a traditional calendar method. The fertile window is calculated by subtracting 13 days (the luteal phase) from the estimated next cycle start date. So I think something similar might be going on here. Thanks in advance!
Posted Last updated
.
Post not yet marked as solved
0 Replies
288 Views
Hello, I want to build an app that will allow the user to entry some health related records and be synced with the HealthKit. Any record that is in the HealthKit is stored locally on the device. I find it conceptually unsure if I should be storing the HealthKit records in the SwiftData to make the user records available across the iCloud synced devices. Should I read the HealthKit record, make a copy of it (including it's ID) on my app's data in SwiftData? How the syncing should be done the right way? thanks.
Posted Last updated
.
Post not yet marked as solved
0 Replies
273 Views
Hello Do we have access to the ECG raw data on the apple watch? I was able to access the data using HKElectrocardiogram Class API. "ecgSample" returns all the recorded ECG logs done by the user using the default apple app. I want to access the data in real-time, do the API supports that? That is, I want to create a custom app in which I direct the user towards recording an ecg signal and then do whatever I want with it. Please let me know, that would be very helpful!
Posted
by zein95.
Last updated
.
Post not yet marked as solved
0 Replies
283 Views
I'm looking at a swimming workout sample and in the metadata I see: Optional(["HKIndoorWorkout": 0, "HKSwimmingLocationType": 2, "HKAverageMETs": 10.7366 kcal/hr·kg, "HKTimeZone": America/New_York]) There is no mention of the HKMetadataKeySwimmingStrokeStyle yet when I look at the workout in the Apple Fitness app, there is stroke style data. How can I access the stroke enum?
Posted
by AndrewH.
Last updated
.
Post not yet marked as solved
0 Replies
273 Views
I'm looking to access the HKMetadataKeyWeatherCondition that indicates the weather during a workout (sunny, cloudy, rain, etc.). I have accessed the workout metadata where I can see temperature and humidity but the weather enum eludes me. Any help would be appreciated.
Posted
by AndrewH.
Last updated
.
Post not yet marked as solved
0 Replies
219 Views
When I record a workout with iPhone, the workout is displayed in the exercise ring. But not with iPad. A workout from iPad is recorded, it is in "Health" app history, but the exercise ring does not display it. Why is the workout not displayed on the exercise ring on iPad?
Posted Last updated
.
Post not yet marked as solved
0 Replies
338 Views
The HealthKit permission sheet is showing up every time the app opens for a few users of my app. It doesn't matter what action they take in the sheet. I have had them try toggling the permissions from the HealthKit system settings but that did not happen to fix the problem. Has anyone experienced this problem or know a fix? Its affecting a few users of my app. I haven't been able to find what in my code could be doing this, I suspect its a bug on HealthKit's side for specific users. I can't find anyone reporting this problem elsewhere so I have to assume its my fault, but the docs clearly state that the permission sheet will only be presented once.
Posted
by steve23.
Last updated
.
Post not yet marked as solved
0 Replies
317 Views
Hi, I can find no way of getting HKSeriesType.heartbeat() data from the health store using my own workout app. The values captured seem to be from the irregular HRV measurements done by Apple. There is a video showing HKHeartbeatSeriesSamples being consumed in an app but not how to capture them from the optical sensor. The WWDC video on this https://stackoverflow.com/questions/77950041/getting-heartbeatseriessamples-in-ios-swift-healthkit-hkanchoredobjectquery at around 28 mins assumes you have written the beats from an external device - not from the optical sensor. I have set typesToRead to be: // Beat addition HKSeriesType.heartbeat(), HKQuantityType.quantityType(forIdentifier: .heartRateVariabilitySDNN)!, // end beat addition Why is the watch app not saving beat to beat interval series to the health store?? Failing that how can the watch app access the data itself so that it can then forward to the companion iPhone app? Help much appreciated.
Posted Last updated
.
Post not yet marked as solved
1 Replies
315 Views
I am reading sleep data from AppleHealthKit API that have wearables connected. Is it possible to retrieve: If data came from wearable (e.g.--> True/False) Wearable brand / Model (e.g. apple or Applewatch2) Software Version (e.g. 1.3.4) Are there specific permissions that need to be asked to retrieve source data?
Posted
by ATGLH.
Last updated
.
Post not yet marked as solved
0 Replies
282 Views
When obtaining the running data of the Apple Watch in the health App, the segmented average heart rate obtained is inconsistent with the data displayed in the health App. Have you encountered it?
Posted Last updated
.