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

Post

Replies

Boosts

Views

Activity

How to export workout plan as JSON?
Hi guys, In WWDC23 session 10016: Build custom workouts with WorkoutKit , the presenters mentioned that a Workout Plan can be exported to a JSON or binary file, and also showed a code snip: let binaryRepresentation = try myCyclingWorkout.dataRepresentation(in: .compactBinary) However in the current SDK, the property dataRepresentation can not be exported with a specific format, the base64EncodedString() result is unreadable. Does anyone know how to export it as a JSON string now? Thanks very much.
0
0
348
Nov ’24
Device Activity Report Per hour Screen-time of apps for Graph
Hi everyone, I need to display a Graph based on Screen-time of apps per hour, from 12Am to 11PM. Am able to get the screen-time data for whole day with each app's total screen-time value. Am kind of confused how can I get the per hour screen-time of apps. I have applied filter of day DeviceActivityFilter( segment: .daily( during: Calendar.current.dateInterval( of: .day, for: .now )! ), users: .all, devices: .init([.iPhone, .iPad]) ) Am also using this data to display apps with their usage just like Apple's Screen_time in settings. I need to display exact same graph just like Apple's screen in phone settings for a Day.
1
0
389
Nov ’24
HKStatisticsCollectionQuery or HKStatisticsCollectionQueryDescriptor
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
1
0
277
Nov ’24
Proper method to handle error in statisticsUpdateHandler?
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 } .. ..
1
0
279
Nov ’24
Apple Watch 8 OS11.2 not synching my activity (intermittently)
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.
0
0
346
Nov ’24
incomplete route data in Apple Health
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?
1
0
211
Nov ’24
HKWorkoutSession.sendToRemoteWorkoutSession doesn't report success or failure
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?
0
0
413
Nov ’24
watchOS app workout doesn't launch
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.
0
0
234
Nov ’24
iCloud Health data not syncing properly with iPhone Simulator on MacOS
As the title says, I logged in to iCloud on my simulator on my mac mini m2 and turned on icloud sync. My health data is in iCloud but it wont load in. When I go to documents for example I can see documents that I have loaded so I know something is working right. I have tried clicking Feature -> Trigger iCloud sync with no luck. I have tried logging out and logging back in, no luck. I have tried Restarting the simulator with no luck. The app I am building uses health data and there is no other way to get health data (heart rate, workouts, sleep) in the simulator. Please help, Thank you
1
1
718
Oct ’24
HKCumulativeQuantitySample does not accumulate values
Hi, My app reports daily step counts, and I’m trying to use HKCumulativeQuantitySample to report them to HealthKit by adding such objects with each update: let sample = HKCumulativeQuantitySample(type: .stepCount, quantity: HKQuantity(unit: HKUnit.count(), doubleValue: dailyTotal), start: startOfDay, end: nowDate) However, HealthKit interprets them as regular samples—it sums them into a global aggregate instead of updating the daily cumulative value. So if I report the daily step count as 500 and then 550, HealthKit interprets it as 1,050 steps instead of 550. Is this expected behavior? If so, what is HKCumulativeQuantitySample intended for, and how should it be used? I’m struggling to find any examples. Thank you
0
0
382
Nov ’24
Unable to retrieve certain data during live workout
I'm currently trying to collect some of the following data whilst running a workout in a WatchOS app I'm building. Below are the data points I'm trying to retrieve: HKQuantityType.init(.heartRate) HKQuantityType.init(.oxygenSaturation) HKQuantityType.init(.respiratoryRate) HKQuantityType.init(.bloodPressureSystolic) HKQuantityType.init(.bloodPressureDiastolic) HKQuantityType.init(.heartRateVariabilitySDNN) I'm using the following delegate function workoutBuilder(_:didCollectDataOf:) which is part of HKLiveWorkoutBuilderDelegate Something I'm realising whilst running this on the simulator and on my Apple Watch is out of all of the Quantity types I'm requesting. Only the heart rate is being called via the delegate function when trying to retrieve the statistic. Is this the intended behaviour of this API? Since there's no docs about what is and isn't exposed
0
0
453
Nov ’24
iCloud Health data not syncing to simulator
As the title says, I logged in to my simulator on my mac mini m2 and turned on icloud sync. My health data is in iCloud but it wont load in. When I go to documents for example I can see documents that I have loaded so I know something is working right. I have tried clicking Feature -> Trigger iCloud sync with no luck. The app I am building uses health data and there is no other way to get health data (heart rate, workouts, sleep) in the simulator. Please help
0
0
332
Oct ’24
Nutrition app 1.4.1. Physical Harm
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.
0
0
405
Oct ’24
Walking speed
I´m working within the health felid with a few apps. Accordingly to science one of the most important parts to keep healthy is every day walking. But it is not to walk slow. You need to come to a little speed (not running or even jogging). But to rais your puls. This is when you get the "real health effect". In general it is around 6km/h. It would be great if apple could make this info available for us developers. I think lots of developers will be happa and use this to make better apps and get more people in a healtheyer life. Looking forward to get some feedback on this. Thank you! Cheers Peter
1
0
397
Oct ’24
Apple Health PDFs
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
0
0
228
Oct ’24
Stands not detected
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!?!?!? 😁🤣
0
0
381
Oct ’24
How to send a simple request when HKObserverQuery triggered in background?
Hi everyone, I am trying to send a request to my server in my watch application when HKObserverQuery is triggered. This is working fine when my app is in foreground however the request is not sending when the app manually terminated or in background. HKObserverQuery works fine and triggered in these cases however the request is not sending. I researched about URLSessionConfiguration.background and background sessions but I could not figure it out. I don't want to download or upload a file, I just want to send a simple request when HKObserverQuery is triggered. Can you show me to a path way to make it possible? I am trying to test my watch app with my iPhone, I am assuming the behavior of these scenarios might be same in both device, am I correct? let urlsession = URLSession(configuration: URLSessionConfiguration.background(withIdentifier: "enablement"), delegate: self, delegateQueue: nil) let dataTask = urlsession.dataTask(with: urlRequest) dataTask.resume() As shown in the code snippet, I tried to set background configuration to my URLSession. I enabled background fetch in background modes. Apple documentation says, dataTask can not run in background -> https://developer.apple.com/documentation/foundation/urlsessiontask However I don't want to perform a long running task such as downloading or uploading.
3
0
733
Oct ’24
Mirroring Workouts Sample Code Doesn't Work With Simulators
I've realised with the sample code from the WWDC video below I'm getting the following error when trying to use the iPhone simulator and apple watch simulator paired. Whenever i try to test out the sample project I'm getting the following error. Failed to send data: Error Domain=com.apple.healthkit Code=300 "Remote device is unreachable" UserInfo={NSLocalizedDescription=Remote device is unreachable, NSUnderlyingError=0x600000c9c900 {Error Domain=RPErrorDomain Code=-6727 "kNotFoundErr ('rapport:rdid:PairedCompanion' not found)" UserInfo={cuErrorDesc=kNotFoundErr ('rapport:rdid:PairedCompanion' not found), cuErrorMsg='rapport:rdid:PairedCompanion' not found, NSLocalizedDescription=kNotFoundErr ('rapport:rdid:PairedCompanion' not found)}}} Is it not possible to not test out the new WorkoutKit mirroring API's using the simulator? Currently right now if you run the project you'll notice that you can start a workout session on the iPhone > Apple Watch but there is no way to control and mirror on both devices at the moment i.e You can't control the iPhone app on the Apple Watch and vice versa. Also because of this the iPhone can't send data to the Apple Watch i.e. pause, end, water etc. I'm guessing this is meant to be possible since it seems a bit strange to only be able to test this out with actual devices. WWDC Session https://developer.apple.com/wwdc23/10023 Sample Code https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/building_a_multidevice_workout_app
2
0
646
Oct ’24
Healthkit HKWorkoutSession state not transitioning
Im building a workout app to track swimming workouts for watchos 11. Triggering .prepare() on my HKWorkoutSession does not change the session state HKWorkoutSessionState. Below is my prepare function which should transition the session state to HKWorkoutSessionStatePrepared. Nothing is thrown in the delegates, the state just wont change? I have tried erasing, restarting, use another version of xcode and another simulator runtime. func prepare() { guard self.session == nil else { fatalError("Session already exist") } // Configure Workout Type let config = HKWorkoutConfiguration() config.activityType = .swimming config.swimmingLocationType = .openWater config.locationType = .outdoor self.Workoutconfig = config // Create Session do { guard store.authorizationStatus(for: .workoutType()) == .sharingAuthorized else { fatalError("Lack of permission to start workout") } let session = try HKWorkoutSession(healthStore: store, configuration: config) self.session = session self.builder = session.associatedWorkoutBuilder() Logger.diveController.info("Successfully created workout session") builder?.dataSource = HKLiveWorkoutDataSource(healthStore: store, workoutConfiguration: config) self.session?.delegate = self self.builder?.delegate = self if self.session == nil { fatalError("No workout session created") } if self.builder == nil { fatalError("No workout builder created") } self.session?.prepare() logger.debug("Session Started at: \(self.session?.startDate ?? Date())") logger.debug("Session State: \(self.session?.state.description ?? "")") if self.session?.state != .prepared { reset() fatalError("Failed To Prepare") } } catch { Logger.diveController.error("Error starting workout session: \(error.localizedDescription)") } }
1
0
676
Oct ’24