HealthKit

RSS for tag

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

Posts under HealthKit tag

96 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SwiftUI: How to create different background colors for List sections?
I'm trying to achieve a specific UI design in SwiftUI where the bottom section of my List has a different background color than the top section. For example in the Medications portion of the Health app, the "Your Medications" Section has a different background than the top "Log" Section. How do I achieve this?: Here some example code. I wonder if I am supposed to use two Lists instead. If I use two Lists though and nest it in a ScrollView, the height of the lists needs to be specified. I am working with dynamic content, though so I don't think that is ideal. class ProtocolMedication {} // Example model struct HomeView: View { @Query private var protocolMedications: [ProtocolMedication] var body: some View { NavigationStack { List { // Upper sections with default background Section { Text("Content 1") } header: { Text("Log") } // Bottom section that needs different background Section { ForEach(protocolMedications) { medication in Text(medication.name) } } header: { Text("Your Medications") } } .listStyle(.insetGrouped) } } }
0
0
40
4h
Deprecated: HKCategoryValueMenstrualFlow
We currently use the HKCategoryValueMenstrualFlow enum to determine the type of menstrual flow: light, medium, etc. a user is having. We also use this enum in determining if it's an actual period day. The Problem I see HKCategoryValueMenstrualFlow was recently deprecated but has not been replaced by another data type. Are there plans to replace/update it with another data type? When or at what point in the future will this deprecation cause a problem in my code?
2
1
117
3d
HealthKit SDK Not Responding When Querying Step Data on iPhone 16 Pro Max
We have working code to fetch step data from HealthKit after requesting the necessary permissions. However, we’ve encountered an issue specific to one device, the iPhone 16 Pro Max. When querying the data, we do not receive a response, and the code enters an infinite loading state without completing the request. The user who is facing this issue has tried logging in on another device, and it works fine. On the problematic device (iPhone 16 Pro Max), the request does not complete. For reference, I’ve included the code below. Resolving this issue is crucial, so we would appreciate any guidance on what steps we can take to troubleshoot or resolve the problem on this specific device. Please note that the device has granted permission to access HealthKit data. static let healthStore = HKHealthStore() static func limitReadFromHealthKitBetweenDates(fromDate: Date, toDate: Date = Date(), completion: @escaping ([HKStatistics]) -> Void) { guard let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount) else { return } let ignoreUserEntered = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyWasUserEntered, operatorType: .notEqualTo, value: true) let now = toDate var interval = DateComponents() interval.day = 1 var calendar = Calendar.current calendar.locale = Locale(identifier: "en_US_POSIX") var anchorComponents = calendar.dateComponents([.day, .month, .year], from: now) anchorComponents.hour = 0 let anchorDate = calendar.date(from: anchorComponents) ?? Date() let query = HKStatisticsCollectionQuery(quantityType: stepsQuantityType, quantitySamplePredicate: ignoreUserEntered, options: [.cumulativeSum], anchorDate: anchorDate, intervalComponents: interval) query.initialResultsHandler = { _, results, error in guard let results = results else { print("Error returned from resultHandler: \(String(describing: error?.localizedDescription))") return } print(results) var statisticsArray: [HKStatistics] = [] results.enumerateStatistics(from: fromDate, to: now) { statistics, _ in statisticsArray.append(statistics) if statistics.endDate.getddmmyyyyslashGMT == now.getddmmyyyyslashGMT { completion(statisticsArray) } } } healthStore.execute(query) } Please note that the code works on all devices except the problematic one. Could you please guide me on the next steps to resolve this issue?
0
0
85
4d
Workout mode drains battery heavily
I am building a watchOS app with iOS companion app. The watch app needs to track the heart rate during the night or while user is sleeping. And the desired frequency of measurement is 0.2Hz (every 5 seconds) For this I am using the HKWorkout mode with mindAndBody session. While it works fine, One of the main issue is: after about 6-7 hours of usage, the battery on the watch drains between 40% (Series 9) and 100% (series 7, I think) My questions: Are there any other option to track user's heart rate without workout, while the app could be in background? Another side effect of this workout mode is, Even if we choose not to save the workout in HealthKit, the Activity rings gets populated by this mindAndBody session, which makes it when the user is waking up, the bar is already full, This is not desired. Is there any option to specify for ActivityRing skips this? Highly appreciate any help in advance. Cheers - Prakash
4
0
195
3d
User-Entered Sleep Data Lacks Time Zone
As a user, there are times when I don't wear my sleep tracker to bed, but I nonetheless want to record my sleep times. Apple Health supports this with the "Add Data" feature, but it's not possible to provide a time zone in the form. Then as a developer, user-added sleep samples are missing time zone information. I would expect that the time zone is requested within the Add Data form. Without this information provided at input time, downstream applications are forced to infer the time zone ourselves, leading to potentially buggy or unintuitive behavior.
0
0
85
1w
Issue with HealthKit Read Permissions on iOS App vs. WatchKitExtension
I'm encountering an issue with HealthKit permissions and would appreciate some guidance: In my app's previous version, I granted write permissions for HKObjectType.workoutType() via the WatchKitExtension. Now, in the upcoming version, I'm trying to request read permissions for both HKObjectType.workoutType() and HKSeriesType.workoutRoute() via the iOS app. However, after granting access: The read permissions for Workout and Workout Route don't show up under Settings -> Health -> Data and Access -> [My App]. The Workout Route permission status remains notDetermined, even though I selected "Allow" when prompted. Interestingly, if I request the same permissions via the WatchKitExtension, everything works as expected, and the issue doesn't occur. Has anyone experienced a similar issue or have insights into why this might be happening? Could it be related to requesting permissions from the iOS app instead of the WatchKitExtension?
0
0
169
2w
Issue with HealthKit Read Permissions on iOS App vs. WatchKit Extension
I'm encountering an issue with HealthKit permissions and would appreciate some guidance: In my app's previous version, I granted write permissions for HKObjectType.workoutType() via the WatchKitExtension. Now, in the upcoming version, I'm trying to request read permissions for both HKObjectType.workoutType() and HKSeriesType.workoutRoute() via the iOS app. However, after granting access: The read permissions for Workout and Workout Route don't show up under Settings -> Health -> Data and Access -> [My App]. The Workout Route permission status remains notDetermined, even though I selected "Allow" when prompted. Interestingly, if I request the same permissions via the WatchKitExtension, everything works as expected, and the issue doesn't occur. Has anyone experienced a similar issue or have insights into why this might be happening? Could it be related to requesting permissions from the iOS app instead of the WatchKitExtension?
0
0
126
2w
HealthKit: Exercise Minutes Not Saving After iOS 18.1 Update
I'm working on an app that reads and writes exercise minutes to HealthKit. Everything functions correctly up to iOS 18.0.1, but starting from iOS 18.1, my implementation is no longer working as expected. Here's the code snippet I use to write to HealthKit: let workout = HKWorkout(activityType: .other, start: startDate, end: endDate) try await healthStore.save(workout) This code successfully writes to both workouts and exercise minutes in iOS 18.0.1 and earlier. However, from iOS 18.1, it only writes to workouts and not to the exercise minutes data source. Has anyone encountered this issue or have insights on how to resolve this?
0
0
204
Nov ’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
219
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
256
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
311
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
219
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
207
Oct ’24
Sleep Analysis inBed sample not recorded on Apple Watch in iOS 18
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
2
2
366
2d
Seeking Feedback on an Idea: Real-Time Siri Running Coach for iOS
Hello everyone, I hope you’re all doing well. I’m not a developer, but I have an idea for an iOS app that I’d love to get your thoughts on. I wanted to share it here to gather feedback from this knowledgeable community and to learn from your expertise. Idea Overview: Real-Time AI Running Coach for iOS The concept is an iOS application that provides personalized, real-time running coaching by leveraging on-device data sources and Apple’s latest technologies. The app aims to offer an adaptive and motivating running experience while ensuring user privacy through on-device processing. Key Features: • Personalized Coaching: • Utilize real-time biometric data and personal insights to deliver AI-driven coaching tailored to the user’s mental and physical state. • Analyze health metrics, activity data, mood check-ins, and more to provide context-based motivational feedback. • Privacy First: • All data processing occurs on-device using Apple’s frameworks like Core ML, ensuring no personal data leaves the device. • Adaptive Motivation: • Implement Natural Language Processing to analyze user inputs like journal entries or mood check-ins. • Generate personalized coaching cues based on historical performance and mood trends. • Performance Enhancement: • Offer dynamic adjustments to pace, route, and strategy in real time to help improve running performance. • Seamless integration with Apple Watch for real-time data collection and haptic feedback. Technologies and Frameworks Involved: • HealthKit: Access health metrics such as heart rate, distance run, VO₂ max, sleep patterns, etc. • Core ML: On-device machine learning for real-time data analysis without latency. • Natural Language Processing: Analyze personal inputs for better coaching personalization. • Core Motion & Core Location: Track motion data and location services for runs. • AVFoundation & Speech: Provide real-time voice feedback and coaching cues. • SiriKit Integration: Allow users to initiate workouts and receive updates via Siri. Target Audience: • Runners of all levels seeking personalized coaching that adapts to their mental and physical states. • Users who prioritize privacy and want AI-driven insights without their data leaving the device. • Tech-savvy fitness enthusiasts who use iOS devices and Apple wearables. Questions for the Community: 1. Feasibility: Is this idea technically achievable using current iOS frameworks and technologies? 2. Data Access: Are there limitations in accessing and processing the necessary data on-device, especially regarding privacy and permissions? 3. Potential Challenges: What hurdles might developers face in creating such an app, and how could they be addressed? 4. Advice: As someone without a technical background, what steps would you recommend I take to move this idea forward? I truly appreciate any feedback or insights you can provide. I’m excited about the potential of this idea but also aware there may be complexities I’m not considering. Thank you for taking the time to read this! Best regards, Paul
0
0
284
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
401
Oct ’24
HealthKit data - Is HKStatisticsCollectionQuery slow?
Hi, I am using HealthKit for the first time. I am using HKStatisticsCollectionQuery. I am running my code iOS 17 on a physical iPhone. It takes several seconds to query data, for example 1 day worth of heart rate at 1 minute resolution. I changed the resolution to 1 hour, expecting it to be faster, but it's pretty much the same… I have been following the official documentation and sample code. I also compiled in Release, but that didn't really help for HKStatisticsCollectionQuery. I quickly looked with Instruments, the app is spending a lot of time in decoding data with NSXPCDecoder. Is there a way to speed data retrieval? Or this is "expected" latency?
2
0
408
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
365
Oct ’24