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

Can we capture beat to beat intervals in a workout app?
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.
0
0
532
Feb ’24
HKCategoryValueSleepAnalysis Sending incorrect sleep data.
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) }
1
0
627
Jan ’24
Need help with Customizing workouts with WorkoutKit
Please reference the Sample Planner app which can be found at the below link. https://developer.apple.com/documentation/WorkoutKit/customizing-workouts-with-workoutkit. In WorkoutStore.swift, all of the values are hard coded. I would like to turn them into variables stored in @EnvironmentObject (WorkoutStoreValue). With the below code, using "singleRunStartDelay" as a trial, I can get that variable passed to the WorkStore struct only when the app is first opened, however, I have not been able to get it changed in realtime. I need help with changing the WorkoutStore struct to have the values updated in realtime. I have tried changing the func from static but that gives an error (Instance member 'createSingleRunWorkout' cannot be used on type 'WorkoutStore'; did you mean to use a value of this type instead?) I'm now learning Xcode/SwiftUI. I have been stuck for about four day trying many different ideas. Thanks // Copyright © 2024 Apple. All rights reserved. /* The structure that returns running workout compositions. */ import HealthKit import WorkoutKit import SwiftUI import Foundation struct WorkoutStore{ @EnvironmentObject var workoutStoreValue: WorkoutStoreValue static func createSingleRunWorkout() -> CustomWorkout { let getReadyStep = WorkoutStep(goal: .open) //fixed to .open let singleRunDelay = WorkoutStoreValue.shared.singleRunStartDelay var onYourMarkStep = IntervalStep(.work) onYourMarkStep.step.goal = .time(Double(singleRunDelay), .seconds) //you have this much time to start var runStep = IntervalStep(.work) runStep.step.goal = .distance(100, .meters) //hard coded for now. Need to insert distance variable here runStep.step.alert = .speed(3...4, unit: .metersPerSecond, metric: .current) // Would like to insert alert variables here var block = IntervalBlock() block.steps = [ onYourMarkStep, runStep ] block.iterations = 1 //fixed at 1. Would like to insert as a variable return CustomWorkout(activity: .running, location: .outdoor, displayName: "Single run mode", warmup: getReadyStep, blocks: [block]) } }
2
0
611
Jan ’24
Can HKWorkout be made Codable?
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.
0
0
497
Jan ’24
Inaccurate query results of HKStatisticsCollectionQuery
I have the same issues, when i use HKStatisticsCollectionQuery query user step count, there's a big difference in the number of steps I'm query before and after a minute's interval. 2023-12-17 15:45:41 steps=529 2023-12-17 15:46:52 steps=5817 2023-12-19 19:43:59 steps=2680 2023-12-19 19:44:31 steps=5554 What is causing this issue? I would like some assistance, please.
0
0
493
Dec ’23
First step in WorkoutKit
Hi there, I'm new here, looking for a step-by-step tutorial that will help me to achieve my first step. https://developer.apple.com/documentation/workoutkit/customizing-workouts-with-workoutkit downloaded the WorkoutKit sample file. try to run, and connect to my account and team but get an error to connect a device. Your team has no devices from which to generate a provisioning profile. Connect a device to use or manually add device IDs in Certificates, Identifiers & Profiles. https://developer.apple.com/account/ " I logged in to my web account but didn't find any device IDs in Certificates, Identifiers & Profiles section
0
0
574
Dec ’23
Workouts created with SingleGoalWorkout do not have a display name, as opposed to workouts created with CustomWorkout. Why is that?
With CustomWorkout, I can assign a name (displayName) to workouts, which also appears in the Workout app. Unfortunately, this parameter is missing for common workouts such as SingleGoalWorkout. Is there a reason for this? I find it inconvenient when the name is missing CustomWorkout init(activity: HKWorkoutActivityType, location: HKWorkoutSessionLocationType, displayName: String?, warmup: WorkoutStep?, blocks: [IntervalBlock], cooldown: WorkoutStep?) SingleGoalWorkout init(activity: HKWorkoutActivityType, location: HKWorkoutSessionLocationType, swimmingLocation: HKWorkoutSwimmingLocationType, goal: WorkoutGoal)
0
0
519
Dec ’23
Reset list of HealthKit written permissions in Setting after remove those from code
After some years our app has been writing some data to HealthKit we decided to remove this functionality from the app. Permissions were removed from requestAuthorization(toShare:read:completion:) method. For new users everything works fine, but for users who were already asked for writing permission in Settings toggles for permissions are still on. Is it any way to update toggles list in Settings for actual state of permissions? Thanks in advance.
0
0
568
Nov ’23
how to check Healtkit's read permission
Even if you have granted read permission for specific health data items (such as walking, weight, etc.), calling the function below will return the permission as 'sharingDenied'. How can I obtain 'sharingAuthorized'? let stepType = HKObjectType.quantityType(forIdentifier: .stepCount)! let authorizationStatus = HKHealthStore().authorizationStatus(for: stepType) //authorizationStatus => sharingDenied
0
0
495
Nov ’23
WorkoutScheduler
Hi, Is there anyway to share a WorkoutScheduler across an iPhone and watch app? If I create a scheduler on the phone app the watch app can't see it and creates its own. I'm using WorkoutScheduler.shared.scheduledWorkouts but end up with two identical sections at the top of the workout app Thanks
0
0
495
Nov ’23
How to use `HKWorkoutBuilder` inside unit tests on iOS 17 and above
With iOS 17 creation of HKWorkout is deprecated via its init functions and the recommendation is to use HKWorkoutBuilder. If you try to init HKWorkout like you would pre iOS 17 you get this warning of deprecation: The problem is that I am creating this HKWorkout object inside unit tests in order to test a service that works with such objects. And HKWorkoutBuilder requires a HKHealthStore which itself requires to be authenticated to be able to create HKWorkoutActivity instances, like it would be when an app is running. But since the unit tests cannot accept the request on the HKHealthStore I am not sure if using HKWorkoutBuilder inside unit tests is possible. I've also tried to inherit HKHealthStore and override all of its methods, but still, store requires authorization. Any ideas on how to proceed with creating HKWorkout for unit test purposes?
0
1
525
Nov ’23
Inconsistent Behaviour in HKWorkoutSessionDelegate Method on watchOS 10.0 and Higher
Hello developers, I hope you're all doing well. I've encountered an issue that I'm struggling to resolve, and I'd greatly appreciate any insights or assistance you can offer. Issue Summary: In my watchOS app, I'm utilizing the HKWorkoutSessionDelegate protocol and the workoutSession(_:didFailWithError:) method. While everything works smoothly on watchOS 9.*, I'm facing a problematic inconsistency on watchOS 10.0 and higher. Steps to Reproduce: Create a new watchOS project with a deployment target of watchOS 10.0 or higher. Implement the HKWorkoutSessionDelegate protocol and the workoutSession(_:didFailWithError:) method. Attempt to start a workout session. Expected Behavior: I expect the workout session to commence without any issues, and the delegate method to gracefully handle any errors, without displaying an error message. Actual Behavior: Unfortunately, on watchOS 10.0 and higher, my attempts to initiate a workout session result in an error message: "Cannot start workout session while process is in the background." Version/Build: Affected watchOS versions: 10.0 and higher Non-affected watchOS versions: 9.* Reproducibility: I've confirmed that this issue is reproducible across different projects and on different simulators running watchOS 10.0 and higher. Additional Information: This inconsistency seems to be specific to watchOS versions 10.0 and higher and doesn't occur on watchOS 9.*. It's causing confusion and hampering my development process, and the error message isn't as informative as I'd like. Workaround: I've been unable to identify a workaround for this issue so far. If any of you have insights, solutions, or suggestions, I'd be grateful for your input. Please feel free to share your experiences and thoughts on this matter. Your help is greatly appreciated! Thank you for your time and assistance. Best regards, Leonid
0
1
384
Nov ’23