Hi!
I am using the HKAnchoredObjectQuery to first get a snapshot of the initial results, and then trigger an updateHandler.
I need to handle the initial results and the updates separately, which is why I implemented two completions.
When I test the code, it works for a while. New and deleted samples trigger the updateHandler. However, after a while there appears an error:
[connection] nw_read_request_report [C2] Receive failed with error "Software caused connection abort"
Followingly, the updateHandler will stop getting triggered when I add updates in Apple health. Anyone have experience with this?
func getMostRecentSample(for sampleType: HKSampleType,
anchorKey: String,
completion: @escaping (HKQuantitySample?, Error?) -> Swift.Void,
updateHandler: @escaping (HKQuantitySample, Error?) -> Swift.Void) {
// If it is the first initialization, anchor is passed as nil
var anchor: HKQueryAnchor? = nil
// Check for previous saved anchor in userdefaults
if UserDefaults.standard.object(forKey: anchorKey) != nil {
let data = UserDefaults.standard.object(forKey: anchorKey) as! Data
do {
guard let newAnchor = try NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: data) else {
print("Could not parse anchor to HKQueryAnchor type")
return
}
anchor = newAnchor
} catch {
print("Error retreiving anchor from UserDefaults")
}
}
let query = HKAnchoredObjectQuery(type: sampleType,
predicate: nil,
anchor: anchor,
limit: HKObjectQueryNoLimit
) { (query, samplesOrNil, _, newAnchor, errorOrNil) in
guard let samples = samplesOrNil as? [HKQuantitySample] else {
fatalError("*** An error occurred during the initial query: \(errorOrNil!.localizedDescription) ***")
}
if let anchor = newAnchor {
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: anchor as Any, requiringSecureCoding: false)
UserDefaults.standard.set(data, forKey: anchorKey)
} catch {
print("Error retreiving anchor from UserDefaults")
}
}
completion(samples.last, nil)
}
// Setting up long-running query
query.updateHandler = { (query, samplesOrNil, _, newAnchor, errorOrNil) in
guard let samples = samplesOrNil as? [HKQuantitySample] else {
fatalError("*** An error occurred during an update: \(errorOrNil!.localizedDescription) ***")
}
if let anchor = newAnchor {
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: anchor as Any, requiringSecureCoding: false)
UserDefaults.standard.set(data, forKey: anchorKey)
} catch {
print("Error retreiving anchor from UserDefaults")
}
}
if let sample = samples.last {
updateHandler(sample, nil)
}
}
self.healthStore.execute(query)
}
Health & Fitness
RSS for tagExplore the technical aspects of health and fitness features, including sensor data acquisition, health data processing, and integration with the HealthKit framework.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I'm developing a single target watchOS app that obtains HealthKit information. I have the "Background Delivery" option checked under "Signing & Capabilities" for the watch target. The app does HKObserverQueries in the foreground that work as I would expect. But when I click the Digital Crown to return to clock face, the HKObserverQuery activity stops. I'm using Xcode 15.4, on Mac 14.5 and a Apple Watch Series 4 running 10.5.
Finally at last Apple Health supports saving .distancePaddleSports, .distanceCrossCountrySkiing, .distanceRowing, .distanceSkatingSports, and much more.
The backstory. In the land of 10,000 lakes, there hasn't been a way to save 'canoe' or 'kayak' distance and I've been asking for it for years. Thank you health team for adding it this year!
FB7807993 - Add HKQuantityTypeIdentifier.paddleDistance for canoeing, kayaking, etc type workouts (June 2020)
Prior we could just save the totalDistance to a workout, but since the HKWorkout initializers were deprecated we no longer have a supported way to save these distances in our workouts. The iOS 18 / watchOS 11 introduction addresses this. If you want to know more why you can't do this in earlier versions you can check these feedback titles:
FB10281482 - HealthKit: Deprecation of totalDistance on a workout session of paddleSports breaks apps that used that to save distance to the workout because there is no "paddleDistance" type available to save as sample data (June 2022)
FB12402974 - HealthKit: Deprecation of HKWorkout completely breaks support for third party fitness apps from saving non-standard workout distance (June 2023)
Great, so there is new support that solves all of these requests and issues for the new version of the OSes. However, the downside is now that there is not much for documentation. Unlike the .runningSpeed and .runningPower introduced in iOS 16 / watchOS 9, none of the new iOS 18 / watchOS 11 types have documentation, at all. To some degree this is understandable, but types from last year still remain undocumented too.
Without this information for the data types introduced in both iOS 17/18 and watchOS 10/11 it makes building and integrating with these new types difficult to say the least. We can't make assumptions about anything.
Can we get a documentation update for new (and existing) quantity types for when Apple Watch will automatically generate samples?
FB14236080 - Developer Documentation / HealthKit: Update documentation for HKLiveWorkoutDataSource typesToCollect for which sample types are automatically collected by watchOS 10 and 11 (July 2024)
FB14942555 - HealthKit / Documentation: App Update Release Issue - HKQuantityTypeIdentifiers are missing documentation describing when the system automatically adds data (today)
I know that the behavior has changed from release to release for some of these types, so documentation would be based on OS version. If you didn't catch it, watchOS 11 will now associate .cyclingSpeed for cycling workouts both indoor and outdoor.
FB12458548 - Fitness: Connected cycling speed sensor did not save samples to health via cycling workout (June 2023 - received reply that only saved for indoor cycling, but not documented otherwise)
FB14311218 - HealthKit: Expected outdoor cycling to include .cyclingSpeed quantity type as a default HKLiveWorkoutDataSource type to collect (July 2024)
To the other third party fitness apps out there, how are you managing the knowledge of which devices collect which data types on which versions of the OS?
Sure, we could look at the HKLiveWorkoutDatSource and inspect the typesToCollect property across a bunch of devices, but again that is trial by error not 'as documented'. Is the behavior of simulators guaranteed to match the behavior of real devices? Maybe, but also maybe not.
Fingers crossed for a nice documentation update to spell out all of the behavioral details.
Apple folks / DTS, many of the above feedbacks are addressed and I plan to update or close them after the releases this fall. Some are still outstanding.
P.S. I hope that .paddleSports gets deprecated and split into individual activity types like skiing did years ago. Their MET scores are different according to the research on the physical activity compendium site.
FB7807902 - Split HKWorkoutActivityType.paddleSports into their own activity types (June 2020)
Topic:
App & System Services
SubTopic:
Health & Fitness
Tags:
Beta
watchOS
Health and Fitness
HealthKit
I'm trying to hook into the new workoutEffort score supported in iOS 18, I am collecting this information from users when they submit their workout and trying to add a sample to the HKWorkout in the same manner as I've been adding other samples like bodyweight, calories burned, etc.
I'm receiving the error:
HKWorkout: Sample of type HKQuantityTypeIdentifierWorkoutEffortScore must be related to a workout
I tried adding the samples using HKWorkoutBuilder.add([samples]) as which has been working perfectly for calories burned & bodyweight, but I am receiving the above error for workoutEffortScore
As a second approach, I tried adding the sample after I called finishWorkout on the HKWorkoutBuilder and received back the HKWorkout object using HKHealthStore.add([samples], to: HKWorkout) and am still receiving the same error!
I don't know otherwise how to relate a sample to a workout, I thought those were the APIs to do so? I'm using Xcode 16.0 RC (16A242) and testing on an iOS 16 Pro simulator
I have FB12696743 open since July 21, 2023 and this happened again today.
I get home at approx 10 mins after the hour, walk appox 50 ft across my yard, up 5 steps into my house, let the dog out and pace on my deck watching the dog, go back in the house walk around the kitchen while preparing dinner. A total of about 200 ft. I sit down about 35 past the hour and start to eat and at 10 mins to the next our and I get the reminder to stand.
On the other side I wake up at 5 mins to hour. Walk 8 steps to the bathroom and successfully achieve the stand for that hour.
WHY!?!?!? 😁🤣
Hi,
In Apple Health, when there is an entry for a visit with a doctor, many times there are accompanying PDFs that are loaded into Apple Health along with the numerical/text data. Is there a way to pull PDFs into an app as well as the numerical/text data?
Thanks
Topic:
App & System Services
SubTopic:
Health & Fitness
In this link, Apple states we can know when a user is in bed vs sleeping and compare their quality of sleep by it. Only, in iOS 18, Apple no longer reports inBed time samples for the Apple Watch. I get why they stopped doing this for the phone, but why the watch? Bug?
My app was using the inBed times for this very purpose and now only works for Garmin and Oura who still report inBed times.
https://developer.apple.com/documentation/healthkit/hkcategoryvaluesleepanalysis
I´m working within the health felid with a few apps. Accordingly to science one of the most important parts to keep healthy is every day walking.
But it is not to walk slow. You need to come to a little speed (not running or even jogging). But to rais your puls. This is when you get the "real health effect". In general it is around 6km/h.
It would be great if apple could make this info available for us developers. I think lots of developers will be happa and use this to make better apps and get more people in a healtheyer life.
Looking forward to get some feedback on this.
Thank you!
Cheers
Peter
Topic:
App & System Services
SubTopic:
Health & Fitness
Tags:
App Tracking Transparency
Developer Tools
SensorKit
HealthKit
Hello everyone,
I’m experiencing ongoing issues with my app’s review process. The app is being rejected under Guideline 1.4.1 (Safety - Physical Harm), and the reason provided is that it doesn’t include appropriate citations for health and medical recommendations.
This app is designed for qualified nutritionists to create personalized meal plans for clients. All recommendations are based on data provided by the client and supported by dietary guidelines from recognized organizations.
We’ve already included multiple citations to credible sources such as:
• USDA
• NIH
• WHO
• University of Oxford
• The Nutrition Source
• ResearchGate
• PubMed
• EUFIC
• DGE
• EFSA
These citations are clearly listed, and all recommendations come from nutritionists with degrees from accredited institutions. Despite this, the app continues to be rejected under 1.4.1. After asking the reviewer for clarification and providing detailed explanations, they’ve stopped responding and only send the same automated response referencing 1.4.1.
Additionally, the client profiles in our app are created via an Admin platform. Should data like height, weight, and other physical metrics be visible in the user’s profile to meet review requirements? We’re wondering if the lack of visible user metrics could be causing this rejection.
Has anyone experienced similar issues or have advice on how to resolve this? We’re uncertain what more we can do at this point and would appreciate any guidance.
Thanks in advance.
Topic:
App & System Services
SubTopic:
Health & Fitness
As the title says, I logged in to my simulator on my mac mini m2 and turned on icloud sync. My health data is in iCloud but it wont load in. When I go to documents for example I can see documents that I have loaded so I know something is working right. I have tried clicking Feature -> Trigger iCloud sync with no luck. The app I am building uses health data and there is no other way to get health data (heart rate, workouts, sleep) in the simulator. Please help
As the title says, I logged in to iCloud on my simulator on my mac mini m2 and turned on icloud sync. My health data is in iCloud but it wont load in. When I go to documents for example I can see documents that I have loaded so I know something is working right.
I have tried clicking Feature -> Trigger iCloud sync with no luck.
I have tried logging out and logging back in, no luck.
I have tried Restarting the simulator with no luck.
The app I am building uses health data and there is no other way to get health data (heart rate, workouts, sleep) in the simulator. Please help, Thank you
Topic:
App & System Services
SubTopic:
Health & Fitness
Tags:
Xcode
HealthKit
Simulator
iCloud Drive
I'm currently trying to collect some of the following data whilst running a workout in a WatchOS app I'm building. Below are the data points I'm trying to retrieve:
HKQuantityType.init(.heartRate)
HKQuantityType.init(.oxygenSaturation)
HKQuantityType.init(.respiratoryRate)
HKQuantityType.init(.bloodPressureSystolic)
HKQuantityType.init(.bloodPressureDiastolic)
HKQuantityType.init(.heartRateVariabilitySDNN)
I'm using the following delegate function workoutBuilder(_:didCollectDataOf:) which is part of HKLiveWorkoutBuilderDelegate
Something I'm realising whilst running this on the simulator and on my Apple Watch is out of all of the Quantity types I'm requesting. Only the heart rate is being called via the delegate function when trying to retrieve the statistic.
Is this the intended behaviour of this API? Since there's no docs about what is and isn't exposed
Topic:
App & System Services
SubTopic:
Health & Fitness
Tags:
Health and Fitness
HealthKit
WorkoutKit
WorkoutKit WorkoutScheduler seems broken with the first beta of iOS 18.2.
I have tested using my app from Xcode and the one that is on the App Store (and working properly on other devices), and it's not working with this new beta of iOS.
They appears in WorkoutScheduler.shared.scheduledWorkouts, but not on the watch.
I even tried with other apps that do the same with
Manual add to Apple Watch with SwiftUI workoutPreview work.
Xcode 16.0
iOS 18.2 Beta 1
WatchOS 11.1
Hi,
My app reports daily step counts, and I’m trying to use HKCumulativeQuantitySample to report them to HealthKit by adding such objects with each update:
let sample = HKCumulativeQuantitySample(type: .stepCount, quantity: HKQuantity(unit: HKUnit.count(), doubleValue: dailyTotal), start: startOfDay, end: nowDate)
However, HealthKit interprets them as regular samples—it sums them into a global aggregate instead of updating the daily cumulative value. So if I report the daily step count as 500 and then 550, HealthKit interprets it as 1,050 steps instead of 550.
Is this expected behavior? If so, what is HKCumulativeQuantitySample intended for, and how should it be used? I’m struggling to find any examples.
Thank you
I am creating a watchOS app with XCode, and am experiencing an issue where workouts do not start on watchOS versions 9.6.3 and later.
・App specifications
Start workout when app starts
code (swift)
workout?.startActivity(with: Date())
·phenomenon
In watchOS version 9.6.3 or later, after the Apple Watch runs out of battery or is turned off.
When you turn on your Apple Watch and start using it, even if you start a workout (startActivity),The status may not change to running and the workout may not work.
*Workout always worked on watchOS versions earlier than version 9.6.3.
*The workout will work if you close the app and start the app again.
If anyone has any information, please provide it.
Topic:
App & System Services
SubTopic:
Health & Fitness
We are seeing an issue where sending data using the asynchronous method HKWorkoutSession.sendToRemoteWorkoutSession(data: Data) will never return in some cases (no success nor failure).
This issue is happening for roughly 5% of Workouts started and will stay broken for the whole workout. The other 95% of the workouts, the connection works flawlessly. This happens on both watchOS 10 and 11, and with phones running iOS 17 or 18. The issue is quite random and not reproducible.
Our app has thousands of workouts a day that use the workout session workout data send, with constant messages being send every few seconds.
In some of those 5% cases the "sendToRemoteWorkoutSession" will throw way later, like 30+ minutes later, if the watch app is awake long enough to capture a log of a failure.
Our code uses the same flow as in the sample project:
https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/building_a_multidevice_workout_app
Here is some sample code, which is pretty simple.
Setup code:
let workoutSession = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
workoutSession.delegate = self
activeWorkoutSession?.startMirroringToCompanionDevice { success, error in
print("Mirroring started on companion device: \(success), error: \(error)")
}
workoutSession?.prepare()
then later we send data using the workout session:
do {
print("Will send data")
try await workoutSession.sendToRemoteWorkoutSession(data: data)
print("Successfully sent data") // This nor the error may be called after waiting extensive amounts of time
} catch {
print("Failed to send data, error: \(error)") // This nor the success may be called after waiting extensive amounts of time
}
So far, the only fix is to restart the phone and watch at the same time, which is not a great user experience.
Is anyone else seeing this issue? or know how to fix this issue?
Topic:
App & System Services
SubTopic:
Health & Fitness
Tags:
Watch Connectivity
Health and Fitness
watchOS
WorkoutKit
When we upload workout data to HealthKit the route information with the workout detailed data is incomplete: just a few dots.
When we select "Show all workout routes" the route data for the same workout shows correctly.
We use the HKWorkoutBuilder to store the workout data, and add the location data with the HKWorkoutRouteBuilder to the workout with
Is this an Apple Health issue, or do we have to change something in the way we store the location data to the workout?
Topic:
App & System Services
SubTopic:
Health & Fitness
My Apple Watch after the beta update is not syncing the activities sometimes with Apple Health.
I just completed a 2.5 km walk, and it showed on Apple Health, yes, but it did not affect my daily goals. This is not the first time this has happened; this is just one of the examples that I'm sharing, other than what has been some problems that I am seeing after the beta update.
Additionally, the camera remote app is not working correctly as I cannot see anything on the watch screen like I used to.
In my app the the statisticsUpdateHandler fetches data from the HealthKit when I open the app from sleeping/standby state. This works fine, except when I leave the app running in the foreground and close the phone for an extended period. This triggers the .errorDatabaseInaccessible error. This seems to stop the statisticsUpdateHandler, maybe set it to nil or something similar. What is the proper way to handle the error to keep it running? As shown in the code below I have tried setting the completion data to the current data. But it stills seems to exit, and thus require a complete restart of the app to re-register the update handler.
Thanks
Tommy
Task {
do {
try await healthStore.requestAuthorization(toShare: [], read:healtTypes)
fetchPast14daysData()
} catch {
print("Error requesting access to health data")
}
}
func fetchDiscreteData(startDate: Date, type: HKQuantityTypeIdentifier, completion: @escaping([WorkoutMetric]) -> Void)
{
let datatype = HKQuantityType(type)
let interval = DateComponents(day: 1)
let query = HKStatisticsCollectionQuery(quantityType: datatype, quantitySamplePredicate: nil, options: .discreteAverage, anchorDate: startDate, intervalComponents: interval)
query.initialResultsHandler = { query, result, error in
...
}
query.statisticsUpdateHandler = { query, statistics, result, error in
var lock_error_detected: Bool = false
// Handle errors here.
if let error = error as? HKError {
switch (error.code) {
case .errorDatabaseInaccessible:
lock_error_detected = true
default:
// Handle other HealthKit errors here.
DispatchQueue.main.async {
self.update_error = error.userInfo[NSLocalizedDescriptionKey] as? String
}
return
}
}
var data = [WorkoutMetric]()
if lock_error_detected {
if (type == .heartRateVariabilitySDNN) {
data = self.HRV
} else {
data = self.restingPulse
}
} else {
guard let result = result else {
completion([])
return
}
result.enumerateStatistics(from: startDate, to: Date()) { statistics, stop in
if ( type == .heartRateVariabilitySDNN)
{
let value = Float(statistics.averageQuantity()?.doubleValue(for: .secondUnit(with: .milli)) ?? 0.0)
//print("HRV data \(value)")
if (value > 1)
{
data.append(WorkoutMetric(date: statistics.startDate, Value: value, Average: 0.0))
}
}
else if ( type == .restingHeartRate)
{
let value = Float(statistics.averageQuantity()?.doubleValue(for: .hertzUnit(with: .none)) ?? 0.0)
//print("Resting hearth rate : \(value) at date \(statistics.startDate)")
if (value > 0.01)
{
data.append(WorkoutMetric(date: statistics.startDate, Value: value*60, Average: 0.0))
}
}
}
let _ = calculate_average(days: self.averagePeriod, workouts: &data)
}
completion(data)
}
healthStore.execute(query)
}
extension HealthManager {
func fetchPast14daysData() {
fetchCumulativeData(startDate: Date().daysAgoAligned(days: daysToFetchDataFor), type: .distanceWalkingRunning) { dailyDistance in
DispatchQueue.main.async {
self.distanceData = dailyDistance
}
..
..
Topic:
App & System Services
SubTopic:
Health & Fitness
Hi,
there seems to be two methods to fetch data from HealthKit and calculate statistics on intervals of the data; HKStatisticsCollectionQuery and HKStatisticsCollectionQueryDescriptor.
I am currently using HKStatisticsCollectionQuery, but HKStatisticsCollectionQueryDescriptor seems to do the same, but with very different code setup.
Could anyone provide any advice on which method is preferable?
Will the older HKStatisticsCollectionQuery become obsolete in the near future?
Thanks
Tommy
Topic:
App & System Services
SubTopic:
Health & Fitness