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

107 Posts
Sort by:
Post not yet marked as solved
0 Replies
77 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
100 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
549 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
117 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
229 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
236 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
202 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
287 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
276 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
259 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
276 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
264 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
209 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
331 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
305 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
309 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
275 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
.
Post not yet marked as solved
1 Replies
322 Views
The edited code still has the problem of not lining up with the health app private func fetchSleepData(for date: Date) { let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)! let endOfPeriod = date let startOfPeriod = Calendar.current.date(byAdding: .day, value: -1, to: endOfPeriod)! let predicate = HKQuery.predicateForSamples(withStart: startOfPeriod, end: endOfPeriod, options: [.strictStartDate, .strictEndDate]) let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { query, samples, error in guard let samples = samples as? [HKCategorySample], !samples.isEmpty else { DispatchQueue.main.async { self.inBedTime = 0 self.coreTime = 0 self.deepTime = 0 self.remTime = 0 self.isSleepDataAvailable = false } print("No sleep data available for date: \(date)") return } print("Fetched \(samples.count) sleep samples for date: \(date)") var inBedTime = 0.0 var asleepTime = 0.0 var deepTime = 0.0 var remTime = 0.0 for sample in samples { print("Sample value: \(sample.value)") let duration = sample.endDate.timeIntervalSince(sample.startDate) / 60 // convert to minutes switch sample.value { case HKCategoryValueSleepAnalysis.inBed.rawValue: inBedTime += duration case HKCategoryValueSleepAnalysis.asleepCore.rawValue: coreTime += duration case HKCategoryValueSleepAnalysis.asleepDeep.rawValue: deepTime += duration case HKCategoryValueSleepAnalysis.asleepREM.rawValue: remTime += duration default: break } } DispatchQueue.main.async { self.inBedTime = inBedTime self.coreTime = coreTime self.deepTime = deepTime self.remTime = remTime self.isSleepDataAvailable = true } } healthStore?.execute(query) }
Posted
by TechyGod.
Last updated
.
Post not yet marked as solved
0 Replies
323 Views
I'm thinking about developing a workout tracking app. To avoid the issue of having to repeatedly download workouts, I want to persist some app model data like Apple does with their Fitness App. At a minimum, the HKWorkout class. Has anyone seen this done before? I'd hate to have reinvent the wheel. HKWorkout: HKSample: HKObject: NSObject.
Posted
by AndrewH.
Last updated
.