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

97 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Can't properly check if Health Kit is authorized.
In my WatchOS app I've written the following code to check if my app has access to the user's health data: func isHealthKitAuthorized() -> Bool { let typesToRead: [HKObjectType] = [ HKObjectType.quantityType(forIdentifier: .heartRate)!, HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!, HKObjectType.quantityType(forIdentifier: .appleMoveTime)!, HKObjectType.quantityType(forIdentifier: .appleExerciseTime)!, HKObjectType.workoutType() ] let typesToShare: Set<HKSampleType> = [ HKObjectType.workoutType(), HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!, HKObjectType.quantityType(forIdentifier: .heartRate)! ] var isAuthorized = true for type in typesToRead { let status = healthStore.authorizationStatus(for: type) if status != .sharingAuthorized { print("Access denied to: \(type.identifier)") isAuthorized = false } } for type in typesToShare { let status = healthStore.authorizationStatus(for: type) if status != .sharingAuthorized { print("Access denied to: \(type.identifier)") isAuthorized = false } } return isAuthorized } However for the appleMoveTime and appleExerciseTime types their status is returning as 'sharingDenied' (checked by printing the status' rawValue) even though they are authorized on the Watch's settings. This happened both on the simulator and on the Watch itself. Am I doing something wrong?
1
0
121
5d
Workout session [session.end()] taking a long time to end
I'm developing a workout app with a mirrored workout session. I'm having problems with sessions being out of sync. For example, when the workout is ended, it takes somewhere around a minute or two for it to actually fully end, so if during this time I start a new workout, then the sessions will be out of sync. I am using healthStore.recoverActiveWorkoutSession() to recover the workout session but it doesn't always work very well and in particular in the case when a workout has been manually ended (but ending hasn't completed) it enters an out of sync mode. The reason why this case is happening is because I have an third party sensor connected to this mirrored workout session and if the sensor is out of range or turned off, I end the workout. However, if the person had accidentally gone out of range, they would reconnect to the app and restart the workout as soon as they realize and in that case, when the workout hasn't fully ended, it doesn't recover appropriately. I have spent weeks trying to debug this with no luck so any advice will be appreciated.
1
0
174
6d
Read Workout Effort Scores
Is there documentation on how to read workout effort scores from a HealthKit workout? I'm interested in reading workoutEffortScore and estimatedWorkoutEffortScore. I have not been successful trying to read them using the same method that I do other workout HKQuantityTypes (heartRate, stepCount, etc). I'm using Swift and I do have authorization for those types requested and granted. I have found documentation on setting these values (https://developer.apple.com/forums/thread/763539) but not reading them. Thank You
2
0
183
1w
HealthKit returns different values depending on the OS the request is made on
Hi, I've had trouble for a while now with HealthKit giving me different values if I make the request on iOS and WatchOS. I am using the exact same method on both with the same parameters but I get vast differences in the results. The code I am using to call HealthKit on both devices is: let dateRange = HKQuery.predicateForSamples(withStart: Date().removeMonths(numberOfMonths: 1), end: Date().endOfDay()) let predicate: NSPredicate predicate = NSCompoundPredicate(type: .and, subpredicates: [dateRange]) let query = HKStatisticsQuery(quantityType: HKQuantityType(.stepCount), quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, error in if error != nil { //print("Error fetching step count, or there is no data: \(error.localizedDescription), \(startDate) -> \(endDate)") onComplete(0) return } if let result, let sum = result.sumQuantity() { let stepCount = sum.doubleValue(for: HKUnit.count()) DispatchQueue.main.async { onComplete(Int(stepCount)) } } } healthStore.execute(query) }
3
0
266
1w
Apple Healthkit data usage
I want to use the Apple Healthkit data to recommend personalised insurance. Is this allowed? As I have read in the documentation that the Apple Healthkit data can only be used for fitness and health purposes. Anyone knows what is meant / scope of "fitness and health purposes"? Will personalised insurance as per health data be allowed under this category?
0
0
116
1w
When does appleExerciseTime update or change?
I've been trying to figure out what the bare minimum is required for HKWorkoutBuilder to create a workout that adds time the appleExerciseTime. I couldn't find the documentation for this. This is my code so far. func createWorkoutSample( expectedActiveEnergyData: [Double], expectedExerciseMinutesData: [Double], calendar: Calendar, startDate: Date ) async throws -> [HKSample] { var testData: [HKSample] = [] let workoutConfiguration = HKWorkoutConfiguration() workoutConfiguration.activityType = .running workoutConfiguration.locationType = .outdoor let results = try await withThrowingTaskGroup(of: HKSample?.self) { group in for (index) in 0..<expectedActiveEnergyData.count { guard let date = calendar.date(byAdding: .day, value: index, to: startDate) else { continue } group.addTask { let builder = HKWorkoutBuilder( healthStore: self.manager.healthStore, configuration: workoutConfiguration, device: .local() ) let endDate = date.addingTimeInterval(expectedExerciseMinutesData[index] * 60) try await builder.beginCollection(at: date) let energyType = HKQuantityType.quantityType( forIdentifier: .activeEnergyBurned )! let energyQuantity = HKQuantity( unit: HKUnit.kilocalorie(), doubleValue: expectedActiveEnergyData[index] ) let energySample = HKQuantitySample( type: energyType, quantity: energyQuantity, start: date, end: endDate ) return try await withCheckedThrowingContinuation { continuation in builder.add([energySample]) { (success, error) in if let error = error { continuation.resume(throwing: error) return } builder.endCollection(withEnd: endDate) { (success, error) in if let error = error { continuation.resume(throwing: error) return } builder.finishWorkout { (workout, error) in if let error = error { continuation.resume(throwing: error) return } continuation.resume(returning: workout) } } } } } } for try await workout in group { if let workout = workout { testData.append(workout) } else { print("Skipping nil workout result.") } } return testData } print("Total samples created: \(results.count)") return results } When I query appleExerciseTime, there are no results. I've looked at the HKWorkoutBuilder documentation, and most of the information expands on adding samples related to the deprecated HKWorkout.
2
0
257
1w
HealthKit permissions not honoring user selection
I'm dealing with a strange bug where I am requesting read access for 'appleExerciseTime' and 'activitySummaryType', and despite enabling both in the permission sheet, they are being set to 'sharingDenied'. I'm writing a Swift Test for making sure permissions are being granted. @Test func PermissionsGranted() { try await self.manager.getPermissions() for type in await manager.allHealthTypes { let status = await manager.healthStore.authorizationStatus(for: type) #expect(status == .sharingAuthorized, "\(type) authorization status is \(status)") } } let healthTypesToShare: Set<HKSampleType> = [ HKQuantityType(.bodyMass), HKQuantityType(.bodyFatPercentage), HKQuantityType(.leanBodyMass), HKQuantityType(.activeEnergyBurned), HKQuantityType(.basalEnergyBurned), HKObjectType.workoutType() ] let allHealthTypes: Set<HKObjectType> = [ HKQuantityType(.bodyMass), HKQuantityType(.bodyFatPercentage), HKQuantityType(.leanBodyMass), HKQuantityType(.activeEnergyBurned), HKQuantityType(.basalEnergyBurned), HKQuantityType(.appleExerciseTime), HKObjectType.activitySummaryType() ] let healthStore = HKHealthStore() func getPermissions() async throws { try await healthStore.requestAuthorization(toShare: self.healthTypesToShare, read: self.allHealthTypes) } After 'getPermissions' runs, the permission sheet shows up on the Simulator, and I accept all. I've double checked that the failing permissions show up on the sheet and are enabled. Then the test fails with: Expectation failed: (status → HKAuthorizationStatus(rawValue: 1)) == (.sharingAuthorized → HKAuthorizationStatus(rawValue: 2)) HKActivitySummaryTypeIdentifier authorization status is HKAuthorizationStatus(rawValue: 1) Expectation failed: (status → HKAuthorizationStatus(rawValue: 1)) == (.sharingAuthorized → HKAuthorizationStatus(rawValue: 2)) HKActivitySummaryTypeIdentifier authorization status is HKAuthorizationStatus(rawValue: 1) With the rawValue of '1' being 'sharingDenied'. All other permissions are granted. Is there a workaround here, or something I'm potentially doing wrong?
1
0
285
2w
Workout not showing for import on Strava
I have a workout app which I am testing on device currently via TestFlight. The generated workout (tennis and indoor) shows in the fitness app with correct HR and duration. However, when I go to my Strava app, it does not show in the list of workouts for importing. (note, activities tracked using the regular tennis mode on the Apple Watch show fine) I have also concurrently reached out to Strava support to see if there's anything they can offer support for. However, does anybody here have any knowledge/experience of the requirement? Or whether this is a limitation of an application deployed via TestFlight? I have a terrible feeling I am chasing ghosts, and it may be a TestFlight limitation for exporting workouts? Thanks
1
0
232
2w
Change displayed metric in Fitness app
Good afternoon, I am working on a workout tracking app. So far everything is working as expected. However, I note that when my workout saves and is visible within the Fitness App, the workout duration is displayed rather than the kCal burned. What changes are required to be made in order for this to display the kCal in the list of workouts in Fitness rather than duration? For reference https://developer.apple.com/videos/play/wwdc2021/10009 this was my reference source for workout functionality.
1
0
239
2w
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) } } }
1
0
250
Dec ’24
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
284
Dec ’24
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?
1
0
290
4w
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
5
0
418
Dec ’24
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
176
Dec ’24
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
254
Dec ’24
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
223
Dec ’24
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
272
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
280
Nov ’24