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
332 Views
I want to verify whether the healthkit data is tampered. Found this article https://developer.apple.com/documentation/healthkit/samples/adding_digital_signatures But it seems that nobody on the internet is talking about this. I want to know the workflow needed to use this feature. Should I store a list of trusted public keys? How can I get the signature and public from the metadata? Anyone with experience on this topic, please share!
Posted
by
Post not yet marked as solved
0 Replies
575 Views
How can I access the mental health record in healthKit to use it in my app? I am developing an application that records how the user feels in some circumstances. At WWDC23, a new iOS application was presented that records this type of data in the health application. I would like to know if it is available to use it in my applications
Posted
by
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
by
Post not yet marked as solved
0 Replies
474 Views
I have two related functions to retrieve the weather and then insert it into a "Live Workout Builder"... The first function calls the second to get the weather info after which it inserts the metadata into the builder. public func stopGatheringLocationData() { logger.info("Stopped gathering location data...") Task { let (humidity, temperature) = await getCurrentWeather() if humidity != nil && temperature != nil { logger.log("Current humidity \(humidity!), temperature: \(temperature!)") let metaData = [HKMetadataKeyWeatherHumidity: humidity!, HKMetadataKeyWeatherTemperature: temperature!] logger.log("Current metadata: \(metaData)") do { try await workoutManager.liveBuilder?.addMetadata(metaData) } catch { logger.error("FAILED to add weather metadata to workout -> \(error.localizedDescription)") } } else { logger.error("FAILED to retrieve weather data...") } } locationManager.stopUpdatingLocation() } private func getCurrentWeather() async -> (humidity: HKQuantity?, temperature: HKQuantity?) { // Get the weather for the starting location... let tempUnit = HKUnit.degreeFahrenheit() let humidityUnit = HKUnit.percent() guard let startingLocation else { logger.error("No starting location...") return (nil, nil) } do { let wx = try await wxService.weather(for: startingLocation) let humidity = wx.currentWeather.humidity let temp = wx.currentWeather.temperature.converted(to: .fahrenheit) let curWx = wx.currentWeather let wxAttr = try await wxService.attribution.legalAttributionText await MainActor.run { currentWx = curWx wxServiceAttribution = wxAttr } return (HKQuantity(unit: humidityUnit, doubleValue: humidity), HKQuantity(unit: tempUnit, doubleValue: temp.value)) } catch { logger.error("FAILED to retrieve weather data -> \(error.localizedDescription)") return (nil, nil) } } The two log statements in the first function print out the following information: [Location/Weather] Current humidity 52 %, temperature: 76.226 degF [Location/Weather] Current metadata: ["HKWeatherTemperature": 76.226 degF, "HKWeatherHumidity": 52 %] However, when I look at the workout in the Activity app on my iPhone, the map generated by my app is present but the weather information is missing. The data looks formatted correctly per the limited documentation but for some reason that data is just not showing up. Any help greatly appreciated...
Posted
by
Post not yet marked as solved
0 Replies
523 Views
Hey everyone, From WWDC23 lab conversations, in order to run a fitness app, health tracking apps, etc. on iPadOS 17 that 'requires' health, you actually have to remove the UI Required Device Capabilities for Health. The UIRDC will still prohibit the app from running on iPad this fall even though from a developer lens it is satisfied. I understand this is to allow iPhone apps a chance to upgrade and get ready for iPadOS 17, but there isn't a path forward if an app truly requires HealthKit. Namely for fitness apps that ONLY read and or write data to Health. Sure I could move my target SDK to 17, but that doesn't help my existing users who can't upgrade on iOS < 17. What is the path forward for Apps that want to target something like the following? iOS 14+ watchOS 7+ iPadOS 17+ Socializing the idea of having an App Store Connect feature or checkbox to allow / opt into being available on iPadOS 17+. The same applies for App Clips that also require HealthKit. FB12327957 - Health / App Store Connect: Ability to make HealthKit required on iPadOS and iOS together
Posted
by
Post not yet marked as solved
0 Replies
513 Views
Relative Date labels on WatchOS complications do not update when in the .WidgetLabel section modifier. Am I missing anything? For example if I want a .accessoryCircular complication in the top centre middle of the Infograph Watch Face, I can have maybe an Icon for the app in the circular slot and then use the .WidgetLabel modifier to display text. However, the Text(Date(), style: .relative) will not update in the WidgetLabel area, but it will update in main area. This is a bug I suspect. This same problem also exists with the .accessory corner complications and the WidgetLabel. The best example of where this works fine currently in the WatchOS system is the Heart Rate complication. Here the WidgetLabel text shows the relative date. It also has formatting options for the date (like only showing minutes), none of this is available to third party developers. Have tested this on the latest public releases of iOS, WatchOS & Xcode as well as the new iOS 17, WatchOS 10 and Xcode 15 Beta releases. Example Code: import SwiftUI import WidgetKit struct WatchWidget: Widget { let kind: String = "WatchWidget" var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: TimelineProvider()) { entry in Text(Date(), style: .relative) .widgetLabel { Text(Date(), style: .relative) } } .configurationDisplayName("WatchWidget") .description("WatchWidget") .supportedFamilies([.accessoryCircular, .accessoryCorner]) } }
Posted
by
Post not yet marked as solved
0 Replies
310 Views
Is Medication tracking features to HealthKit have read/write access to developers from ios 17.
Posted
by
Post not yet marked as solved
1 Replies
496 Views
I would like to create an Apple Watch only app that queries data such as blood oxygenation, heart varibility, number of steps, energy consumed, and other data of a similar nature recorded over the past month and performs calculations on them. I read from the HealthKit documentation that Apple Watch synchronizes data with iPhone and periodically deletes older data, and that I can get the date from which the data is available with earliestPermittedSampleDate(). Is there a risk that in general, by making queries to retrieve data up to a month old, the data will no longer be available? I need the app to work properly without needing an iPhone.
Posted
by
Post not yet marked as solved
0 Replies
449 Views
I am attempting to query HealthKit for Vision Prescriptions. The query below is able to return results back that I have saved to HealthKit, however, I am having trouble accessing the HKVisionPrescription metadata such as the HKGlassesLensSpecification for both the Right and Left Eye. I am only able to access properties like prescriptionType and dateIssued. I created these record programmatically so I know the values I am looking for exist and I am able to confirm their existence in the Health app. How can I modify this code so I can access the finer details of each prescription? func getPrescriptions() async -> [HKVisionPrescription] { let datePredicate = HKQuery.predicateForSamples(withStart: start, end: end) // Predicate that matches vision prescriptions samples let predicate = HKSamplePredicate.visionPrescription(datePredicate) let descriptor = HKSampleQueryDescriptor( predicates:[predicate], sortDescriptors: [], limit: 10) do { let results = try await descriptor.result(for: store) if results.isEmpty { await requestPermission() return [] } results.forEach { prescription in // How to access prescription metadata here? } return results } catch { print("no error from query") return [] } }
Posted
by
Post not yet marked as solved
0 Replies
370 Views
We have an app that tracks steps, distance, calories ... Now we want to push the data into Apple Health. The iPhone is tracking data by itself so I'm wondering if I should simply push the data we measured (which will be added to the existing data) or if I should calculate the difference from existing data to our measured data and just add what's missing. Example: Apple measured 500 steps from 11-12 am. Our bracelet measured 800 steps. While the phone might have been lying somewhere and the bracelet has always been worn, I rely on the bracelet data. So do I push 800 steps or 300 steps ? Many thanks, Sven
Posted
by
Post not yet marked as solved
2 Replies
1k Views
I am running iPadOS 17 beta2 and experiencing an issue with the integration between a third-party app and the Health app. Specifically, I have noticed that the isHealthDataAvailable() method in HealthKit is returning false. Additional Information: ・Device: iPad (6th generation) running iPadOS 17 beta2. ・Xcode: ver14.2.0 Expected Outcome: ・I expect the isHealthDataAvailable() method in HealthKit to return true. This would allow the third-party app to integrate with the Health app. Additional Details: ・The third-party app successfully integrates with the Health app on iOS 17 beta2. ・The issue occurs regardless of whether the Health app is installed or uninstalled. I would greatly appreciate any advice or solutions regarding this issue. Thank you for your assistance.
Posted
by
Post not yet marked as solved
0 Replies
522 Views
I'm trying to make a simple workout app that gets data from the health app (not an app that you use the record the actual workout). I can get data from the health app and manually add workouts but I couldn't find out how to record one with a map. Is there a way for me to either upload a GPX file for the workout, record it on the watch, or some other way to get the workout with a map on the simulator.
Posted
by
Post not yet marked as solved
0 Replies
409 Views
Hi! I am trying to build a fitness app and running it on an iPhone simulator. So far, the app is working and can detect workouts and display them. Now, I want to make the app work for workouts that have a map but I couldn't find how to add a map or any other kind of data without recording it on the apple watch which I can't do because there is no workout app displayed on the simulated watch. Thanks.
Posted
by
Post not yet marked as solved
0 Replies
471 Views
Has anyone used healthDataAccessRequest successfully in SwiftUI? How does parameter trigger work?
Posted
by
Post not yet marked as solved
3 Replies
874 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
Post not yet marked as solved
0 Replies
301 Views
I have a question regarding the number of steps that can be retrieved from HealthKit. Is there any difference in the result of the number of steps when the number of steps is acquired immediately after walking and when it is acquired 10 minutes later? For example, the following image. First, the data is acquired from HealthKit and 0 steps are returned. Within 1 minute, the user takes 50 steps. Immediately after taking 50 steps, data is retrieved from HealthKit and 0 steps are returned. After 10 minutes, HealthKit retrieves data and returns 50 steps without taking a single step. Sometimes the correct number of steps is obtained immediately after walking, and sometimes the correct number of steps is not obtained until some time has elapsed.
Posted
by
Post not yet marked as solved
0 Replies
317 Views
I have code that's been in production for a year and never had any issues reading BMI. One of my users just submitted a bug report saying that attempting to read BMI data crashed the app. The error Xcode shows is 'Attempt to convert incompatible units: count, kg/m^2'. Now I'm pretty sure the unit for BMI shouldn't be "count" so what the heck is going on? Is this a bug? This is happening on watchOS 9.5.2. Please note that this app version was released to the App Store a year ago and worked at that time (and presumable until recently).
Posted
by
Post not yet marked as solved
0 Replies
407 Views
So, I've wrote the following code; let status = healthStore.authorizationStatus(for: .activitySummaryType()) switch status { case .notDetermined: return false case .sharingDenied: return false case .sharingAuthorized: return true @unknown default: return false } And it is hitting the .sharingDenied case. This doesn't make sense as on my phone I have allowed read access (there's no sharing option per the documentation). As soon as I change out to let's say; let checkHkQuantityTypeAuthorization = HKObjectType.quantityType(forIdentifier: .stepCount) I am able to hit the case .sharingAuthorized case. What doesn't make sense is that even though it fails this check, if I just go ahead and query for the Activity Summary for the ring data via; let predicate = HKQuery.predicate(forActivitySummariesBetweenStart: startDateComponents, end: endDateComponents) let query = HKActivitySummaryQuery(predicate: predicate) { (query, summaries, error) { ... } It works just fine and I can pull the Activity data without changing any permissions in the Privacy settings of my iPhone or iPad. So, I know I can pull the data just fine, and that everything is set correctly for the Entitlements. I just want to make sure that the user has actually allowed me to before I try to pull the data. Additional Notes: The REALLY weird thing is that that when I try to pull the .stepCount, is that it will hit the .sharingDenied case if I only have the user do READ access. So, I've had to make my app also request for WRITE (share) access. Like this doesn't make any sense for me to request both READ and WRITE access to step count when my app only needs read access (like Activity Summary data). This seems like a bug in my opinion as I don't see anything related in the documentation in regards to this on the If this is how this is supposed to work given the discussion on the documentation; To help prevent possible leaks of sensitive health information, your app cannot determine whether or not a user has granted permission to read data. If you are not given permission, it simply appears as if there is no data of the requested type in the HealthKit store. If your app is given share permission but not read permission, you see only the data that your app has written to the store. Data from other sources remains hidden. Source: https://developer.apple.com/documentation/healthkit/hkhealthstore/1614154-authorizationstatus Then that is completely confusing. I want to check if I have permissions to read this data otherwise why bother trying to read the data or try to present anything to the user except that they need to allow access to me reading this data. Apple says that you should only request to relevant Health data when you need it. So this check is worthless if I am trying to check before I do the query because the UI wants to display data in regard to activity data. Honestly, this is really confusing if all this falls into the discussion item on the documentation and Apple needs to do better. EDIT: Further reading the very top of the method definition yields; Returns the app’s authorization status for sharing the specified data type. Like why Apple? I want to know if I can READ the type so I can tell the user to allow me access or not. This is frustrating.
Posted
by
Post not yet marked as solved
2 Replies
666 Views
I'm trying to find out if the new "Time in Daylight" feature in the Health app has a corresponding HealthKit data type that our app will be able to query in the release versions of iOS 17 / watchOS 10. So far, I cannot find any reference such a type in beta documentation. Can someone confirm if this will be available? Please note that this is not an inquiry about data collection for "Time in Daylight." We are successfully seeing samples collected on our Watch/iPhone pair running the latest betas.
Posted
by