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

106 Posts
Sort by:
Post not yet marked as solved
0 Replies
276 Views
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
Posted Last updated
.
Post not yet marked as solved
2 Replies
450 Views
In the wwdc2023-10023 session, we go over how the Apple Watch can be used as a primary workout session manager and the iPhone as the mirrored one. How is it possible to create a workout session on the iPhone and optionally mirror it to the Apple Watch to collect heart rate data? In iOS 17, I still cannot instantiate a HKWorkoutSession, I'm assuming it says it's available because we can have an instance of it as a mirrored copy from the Apple Watch. I find it odd that the iPhone cannot manage the primary session. I hope I'm missing something.
Posted Last updated
.
Post marked as solved
2 Replies
372 Views
iPadOS 17 brings HealthKit to the iPad. So I've updated my HealthKit-using app to also run on iPadOS. I can debug it from Xcode on iPad simulators and my iPad, but when I upload a build to AppStoreConnect from Xcode and try to install it on my iPad from TestFlight, the install-button is missing and instead there is a label saying "incompatible hardware". The app has no other required device capabilities besides healthkit. It was also updated to at least require iOS/iPadOS 17. I can install it on my iPhone but not on the iPad. I also noticed that in this list https://developer.apple.com/support/required-device-capabilities/#ipad-devices no iPad model has the healthkit device capability. Why? Is there some way to find out why exactly TestFlight thinks the iPad is incompatible hardware? Thanks in advance to anyone who can enlighten me here.
Posted
by rbeeger.
Last updated
.
Post not yet marked as solved
0 Replies
397 Views
Hi, with iOS 17 creation of HKWorkout is deprecated via its init functions and the recommendation is to use HKWorkoutBuilder: 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. Any ideas on how to proceed with creating HKWorkout for unit test purposes?
Posted
by Amiorkov.
Last updated
.
Post marked as solved
1 Replies
506 Views
Hi Is there a way to read the sleep schedule i have set in either the health or clock apps? I found a few posts on here asking the same thing and the responce was always either no or just no responce but they are all from over 2 years ago so im not sure if something has changed since then. Up untill recently i was using a shortcuts automation to get the data but a recent update started excluding the sleep schedule alarm from the list that the shortcuts app can pull from the clock app. I dont want historical data, just when the alarm is set to go off next. I was using it to turn my lights on dim half an hour before the alarm goes off without having to set the schedule in 2 places. I have an annoyingly inconsistent morning schedule. Thanks
Posted
by TomW1605.
Last updated
.
Post not yet marked as solved
0 Replies
410 Views
The app I distribute has a function that retrieves step count information from the "Healthcare" app and displays it on the app, but depending on the device, the step count may not be retrieved. When I checked the settings of the "Healthcare" app, I found that it was properly linked to the app, but for some reason I was unable to retrieve it. Is there any countermeasure in such a case? Is there anyone who has experienced a similar incident?*The same issue occurs even if the device is changed and the same Apple ID is used, so I think it is caused by the Apple ID.
Posted Last updated
.
Post not yet marked as solved
1 Replies
416 Views
Hi, I am having some trouble with uploading HealthKit data to AWS S3 in the background. As of now, when I click on the button to beginBackgroundUpdates the data is uploaded as expected. When I go off the app and add data to HealthKit nothing happens. When I go back to the app, the new data is uploaded. I am not sure why this is not happening in the background. More specifically, I am not sure if this is allowed, and if so what I am doing wrong. ContentView: import SwiftUI import HealthKit struct ContentView: View { @StateObject var healthKitManager = HealthKitManager() var body: some View { VStack { Button("Enable Background Step Delivery") { healthKitManager.beginBackgroundUpdates() } } .padding() .onAppear { healthKitManager.requestAuthorization { success in print("Configured HealthKit with Return: \(success)") } } } } #Preview { ContentView() } BackgroundDeliveryApp: import SwiftUI import HealthKit import Amplify import AWSS3StoragePlugin import AWSCognitoAuthPlugin @main struct HKBackgruondDeliveryApp: App { private func configureAmplify() { do { try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.add(plugin: AWSS3StoragePlugin()) try Amplify.configure() print("Succesfully configured Amplify with S3 Storage") } catch { print("Could not configure Amplify") } } init() { configureAmplify() } var body: some Scene { WindowGroup { ContentView() } } } HealthKitManager import Foundation import HealthKit import Amplify struct TestStep: Encodable, Decodable { let count: Double let startDate: Date let endDate: Date let device: String } class HealthKitManager: ObservableObject { var healthStore: HKHealthStore? let stepType = HKObjectType.quantityType(forIdentifier: .stepCount) let heartRateType = HKQuantityType(.heartRate) let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) init() { if HKHealthStore.isHealthDataAvailable() { healthStore = HKHealthStore() } else { print("There is no health data available") healthStore = nil } } func encodeStepList(stepList: [TestStep]) -> Data{ let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 do { return try encoder.encode(stepList) } catch { return Data() } } func uploadStepData(stepList: [TestStep]) async { let stepData = self.encodeStepList(stepList: stepList) let uploadTask = Amplify.Storage.uploadData( key: "ExampleKey", data: stepData ) Task { for await progress in await uploadTask.progress { print("Progress: \(progress)") } } do { let value = try await uploadTask.value print("Completed: \(value)") } catch { print("Could not upload step data") } } func requestAuthorization(completion: @escaping (Bool) -> Void) { guard let stepType = stepType, let sleepType = sleepType else { return completion(false) } guard let healthStore = self.healthStore else { return completion(false) } healthStore.requestAuthorization(toShare: [], read: [stepType, heartRateType, sleepType]) { success, error in if let error = error { print("Some error has occoured during authorization of healthKit") print(error) } return completion(success) } } func beginBackgroundUpdates() { guard let healthStore = healthStore, let stepType = stepType else { print("Cannot begin background updates because HealthStore is nil") return } healthStore.enableBackgroundDelivery(for: stepType, frequency: .immediate) { success, error in print("Background update of health data") if let error = error { print("Some error has occoured during the set up of the background observer query for steps") print(error) return } guard let query = self.createObserverQuery() else { print("Could not create a query for steps") return } healthStore.execute(query) } } func stepCountDeviceRecordsQuery(stepCountObjects: @escaping ([TestStep]) -> Void) { guard let stepType = stepType else { print("Nil step type") return } let stepCountUnit = HKUnit.count() let endDate = Date() let startDate = Calendar.current.date(byAdding: .day, value: -7, to: endDate) let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate) let sortDescriptors = [NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true)] let stepCountQuery = HKSampleQuery(sampleType: stepType, predicate: predicate, limit: 10000, sortDescriptors: sortDescriptors) { query, results, error in if let error = error { print("Error in getStepCount") print(error) return } guard let results = results else { print("Empty results in getStepCount") return } var stepCounts: [TestStep] = [] for (_, record) in results.enumerated() { guard let record: HKQuantitySample = record as? HKQuantitySample else {return} let step = TestStep(count: record.quantity.doubleValue(for: stepCountUnit), startDate: record.startDate, endDate: record.endDate, device: record.device?.model ?? "") stepCounts.append(step) } print("\(stepCounts.count) records at \(Date())") print(stepCounts[stepCounts.count - 1]) stepCountObjects(stepCounts) } healthStore?.execute(stepCountQuery) } private func createObserverQuery() -> HKQuery? { guard let stepType = stepType else { return nil } let query = HKObserverQuery(sampleType: stepType, predicate: nil) { query, completionHandler, error in self.stepCountDeviceRecordsQuery { stepList in Task { await self.uploadStepData(stepList: stepList) } } completionHandler() } return query } }
Posted
by VMoorjani.
Last updated
.
Post marked as Apple Recommended
682 Views
I am having trouble getting the new mirroring session API to send data to the companion device. when starting a workout on my watch I call startMirroringToCompanionDevice and then go onto my iOS workout manager to handle it via the workoutSessionMirroringStartHandler, I set the delegate here and can confirm that it is indeed not nil within that function but when I go to send some data across I get an error saying the remote session delegate was never set up. I noticed this same behaviour in the WWDC demo and have been unable to find a solution that will allow me to send data across the mirrored session even though I am able to control the workout session state(pause, resume, end) on both Phone and Watch. Has anyone else encountered this issue? Anyone have a solution?
Posted
by sebrob.
Last updated
.
Post not yet marked as solved
0 Replies
413 Views
Hi guys, I'm delveloping an app that use HealthData. I use this data: HKWorkoutType.workoutType(), HKObjectType.quantityType(forIdentifier: .heartRate)!, HKObjectType.quantityType(forIdentifier: .distanceSwimming)! I would like use Simulator to test app, but there aren't data. How can I import data? Now to test my app use only my iPhone, but in this way I don't test multiple device to test my app. Could you help me? Thank you. Filippo
Posted
by gatfil.
Last updated
.
Post not yet marked as solved
3 Replies
898 Views
I'm trying to query HealthKit for all of users medications, including prescribed medications and user-entered medications. Using a HKSampleQuery with type HKClinicalTypeIdentifierMedicationRecord, I'm able to fetch medications that have been prescribed by a healthcare provider (eg medications associated with clinical FHIR records): let type = HKClinicalType(.medicationRecord) let predicate = HKQuery.predicateForClinicalRecords(withFHIRResourceType: .medicationStatement) let query = HKSampleQuery(sampleType: type, predicate: predicate, limit: kRecordLimit, sortDescriptors: nil) { q, samples, error in // this returns only -clinical- records // it doesnt include manually entered meds } However, medications which I have manually entered into the Health app with a user-defined schedule and dosing do NOT appear in the results of this query. is it possible to fetch medications which have been manually entered by the user?
Posted
by cdstamper.
Last updated
.
Post not yet marked as solved
4 Replies
958 Views
For some reason I am not receiving HKQuantityTypeIdentifierDistanceSwimming samples when using the watchOS 10 beta (8). The same code works fine on watchOS 9 but not on watchOS 10. I have tried specifically enabling them in the collection types for the live builder and /or starting a query for them, but neither approach is causing any samples to be returned to the app. Is this a known issue? Has something changed for swimming in watchOS 10? Thanks in advance.
Posted
by cfc.
Last updated
.
Post not yet marked as solved
1 Replies
468 Views
When the build a multi-device workout app sample project is ran, there is a problem that stops workouts from being logged with only the watch. When the workout is started from the Apple Watch with the iPhone app closed, you can usually end the workout from the watch in the first few seconds. However, if the workout lasts more than 30 seconds, when the workout is ended via the watch, everything will stall for multiple minutes or indefinitely until the iPhone app is opened. How is it reccommended to fix this issue? It makes the sample project unusable for production as is because many users may want to sometimes log a workout with their watch without the iPhone present. I haven't been able to figure out a good solution, can someone please help with this.
Posted Last updated
.
Post not yet marked as solved
0 Replies
383 Views
At the moment I am working on a small app that retrieves Activities via HealthKit and allows user to trim activities. A typical use case would be when an user forgets to finish / stop an activity recording on his watch. Has anyone experience with submit such kind of apps to the app store. Does apple even allow this kind of feature? It could harm the integrity of health data if not done correctly.
Posted Last updated
.
Post not yet marked as solved
3 Replies
615 Views
I am trying to get heart rate data from health store but when I make a query there are samples that come through with timestamps that shows that there are minutes that go by between the sample measurements. I remember watching an apple video where they were talking about the Quantity series and how these series have one kind of container for multiple data points of bpm data. I also see in the samples that there is a unit of " ___ counts per second" for each of the results so it would make sense if there were multiple datapoints within each of the results from the query but I don't know how to see what's inside of the results or if there is even anything more to them. This is the code I am using to retrieve the data: public func fetchLatestHeartRateSample(completion: @escaping (_ samples: [HKQuantitySample]?) -> Void) { /// Create sample type for the heart rate guard let sampleType = HKObjectType .quantityType(forIdentifier: .heartRate) else { completion(nil) return } /// Predicate for specifying start and end dates for the query let predicate = HKQuery .predicateForSamples( withStart: Date.distantPast, end: Date(), options: .strictEndDate) /// Set sorting by date. let sortDescriptor = NSSortDescriptor( key: HKSampleSortIdentifierStartDate, ascending: false) /// Create the query let query = HKSampleQuery( sampleType: sampleType, predicate: predicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: [sortDescriptor]) { ( _, results, error) in guard error == nil else { print("Error: \(error!.localizedDescription)") return } print(results ?? "Error printing results.") completion(results as? [HKQuantitySample]) } healthStore.execute(query) } Ultimately I want the most frequent heart rate data that is available. Ideally a bpm measurement every 5 - 10 seconds or less. Is this possible if I have not explicitly saved this heart rate data to the health store for a user before trying to access it or does Apple store all of this information in the health store regardless of the circumstances? Any help is greatly appreciated!
Posted
by AppleJm.
Last updated
.
Post marked as solved
1 Replies
507 Views
I am working with Apple HealthKit, and I need to add functionality to my app that allows a user's Apple Watch to automatically send the relevant data for their workout session (e.g. vo2 max, start timestamp, end timestamp, heartbeat, duration etc) as soon as they end their workout. This would need to work for any type of workout they do. E.g. if they are doing a running session, when they end their workout my app needs to receive the data for that running session almost instantly. I know that enableBackgroundDelivery allows my app to listen to changes in Apple Health in the background, but I'm not sure which method in HealthKit will allow me to implement the above use case. Does anyone have any pointers? I just want to know what methods in HealthKit will allow me to achieve this.
Posted
by DanielRN.
Last updated
.
Post not yet marked as solved
6 Replies
1.4k Views
When I update a variable inside my model that is marked @Transient, my view does not update with this change. Is this normal? If I update a non-transient variable inside the model at the same time that I update the transient one, then both changes are propagated to my view. Here is an example of the model: @Model public class WaterData { public var target: Double = 3000 @Transient public var samples: [HKQuantitySample] = [] } Updating samples only does not propagate to my view.
Posted Last updated
.
Post not yet marked as solved
0 Replies
372 Views
Hey team! I have a question that feels very obvious, but I cannot seem to find the answer in the documentation. Using HealthKit/WorkoutKit, how you can make workouts with different activity types? Say you do 10 minutes of traditionalStrengthTraining followed by 10 minutes of running (common for crossfit and similar high intensity workout styles)? From the docs, it looks like you can’t change the activity type on an HKWorkout and the new dividing workouts into activities concept seems to only be for swimBikeRun workouts. Do you simply make multiple consecutive HKWorkoutSession instances, e.g doing startActivity -> beginCollection -> endCollection multiple times? Any input is highly appreciated!
Posted Last updated
.
Post not yet marked as solved
0 Replies
274 Views
Hello! I was wondering whether or not it was possible for: An application to programmatically open up an Apple app (i.e. navigate to the ECG app on the Apple Watch for my case) through some framework or internal URL? A background thread of my running application (which is occurring through a workout session) to issue a command to come back to it's main page of the application? This would help in a systematic data-gathering flow which requires me to gather ECG data and then return to the application for further action without too much action on the user's behalf. Thank you!
Posted
by reskrit.
Last updated
.
Post not yet marked as solved
0 Replies
395 Views
We have an app that reads data from the Apple Health Kit that is about 5 years old and we stopped receiving data from the app. While investigate why it quit working we are seeing some messages in the console log when we plug a phone into a mac that we are trying to get clarification on. We are seeing from the log: healthd 'STARTING: com.apple.healthkit.background-delivery.:<thread?>' followed by a: dasd 'COMPLETED com.apple.healthkit.background-delivery.:<thread?> at priority 30 then a dasd 'NO LONGER RUNNING com.apple.healthkit.background-delivery.:<thread?> ... Tasks running in the group [com.apple.dash.default] are 1! I was looking for some clarification on what these messages mean. Do they mean that our app was started and that the process completed successfully or, is it a warning saying that something abnormal happened. Also, I'm coming up short on documentation when I google for these messages. Is there a repository out there to help me make sense of what I'm seeing? Thanks for any insight!
Posted
by TheNoob55.
Last updated
.