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

102 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Is it possible to provide an interface for real-time sleep status monitoring
Apple Watch automatically tracks sleep data and syncs it to the iPhone, making it available through HealthKit for historical analysis. However, there is no way to retrieve real-time data on whether a user has entered sleep, or whether they are in a specific sleep stage at any given moment. Is it possible to provide an interface for real-time sleep status monitoring
1
0
27
1h
HealthKit: Seeking Guidance on Continuous, Near Real-Time Heart Rate Data Conitnously in IOS Application
Dear Apple Developer Support, I am writing to request assistance with an ongoing issue I'm encountering while developing an iOS application that utilizes HealthKit to fetch heart rate data. My goal is to display near real-time heart rate updates continuously same as displaying in the Apple Watch , I want to show in the iPhone Mobile Application for fitness related. I have implemented the following approaches: HKSampleQuery with a Timer: I've set up a timer to periodically fetch the latest heart rate data. Despite these efforts, I'm consistently facing the following problems: Delayed Updates: The heart rate data displayed in the app often doesn't reflect the current heart rate being measured by the Apple Watch. There seems to be a significant synchronization delay. Inconsistent Background Updates: Background updates, even with background app refresh enabled, are not reliable. The app often only updates when brought to the foreground or after being killed and relaunched. Entitlements: The com.apple.developer.healthkit.background-delivery entitlement error is missing. I have thoroughly reviewed Apple's HealthKit documentation, implemented best practices for HealthKit integration, and verified that all necessary permissions are properly configured. I understand that HealthKit may not be designed for true real-time data, but the current level of delay and inconsistency is making it difficult to provide a useful user experience. Could you please provide guidance on whether achieving near real-time heart rate updates continuously in an iOS app using HealthKit is possible? If so, what are the recommended strategies and best practices to overcome these limitations? I have also tested the application on physical devices with Apple Watch, enabled background app refresh, granted permissions, and referred to HealthKit documentation. I would appreciate any insights or suggestions you can offer to help resolve this issue. Thank you for your time and assistance. Sincerely, Venu Madhav
1
0
140
1d
[Error] 18.2.1 HealthKit steps
From the date the app was updated, the step count data retrieved from HealthKit was strange. On the other hand, step count data from the date before the update is imported normally. After deleting and reinstalling the app, the problem did not occur. Is there anyone who has experienced something like this or knows the cause?
1
0
254
1w
Adding segments/splits into workout
Hello, I am building a workout app that has an option to add segments to differentiate different stages of the training session. Segments are added the following way: func saveSegment(eventType: HKWorkoutEventType, startDate: Date, endDate: Date, inSeg: Int) async throws { let dateInterval = DateInterval(start: startDate, end: endDate) let event = HKWorkoutEvent(type: eventType, dateInterval: dateInterval, metadata: metadata) try await builder?.addWorkoutEvents([event]) } Inside Health -> Workouts -> Show All Data, the segments appear, but in Fitness app there are no segments. The workout is .paddleSports. I thought that maybe the workout type was the problem, but when I start the sessions from the native workout app, segments are added and shown in the Fitness app: In other posts I saw suggested to add an event as .marker instead of .segment, but the result is the same, it does not appear. Is there something I am doing wrong? How can I show the segments into the Fitness app? Another question, I would like to add stroke rate and stroke count to my paddling session, is there a way to add it? Paddle Sports workout was recently introduced and it would be great to have the option to add those values. Thank you in advance. Inaki
0
0
360
3w
Location of indoor workouts
In the fitness app under iOS 18, the location of all workouts is displayed on a small map. For workouts with routes, I can already successfully read out the route and thus also determine the starting point. So that works. For indoor workouts such as yoga or indoor rowing, the exact location is also displayed in the fitness app. I would now also like to read out this location for these indoor workouts in my app. Does anyone know how to do this?
1
0
379
3w
Extended Runtime Session vs HKWorkoutSession Issues
I am working on an Apple Watch companion app to an existing live iOS app. I am utilizing the heart rate tracking for an active 'self-care' sauna session. I say self-care in quotes because it's more self-care than a workout activity, but it is closely blurring the lines between the two. I have come to understand that if a session truly isn't a workout, then you should not use workoutSession.startActivity. However the app needs to function entirely like a workout would. This is not a meditation application. Sauna is actually just one of many activity types supported in the app. I have tried using extended runtime session, and there have been numerous issues with doing so. It is not nearly as robust for the user. For example, the active session is not prioritized by the watch's CPU. Now playing is no longer functional. Heart rate is far more inconsistent, and this variable is as critical as if it were in a workout. I have tried using HKWorkoutSession, however I worry the app will be rejected by doing so. This method works most accurately to collect the right data for the user, and prioritizes system resources as expected. The app can be moved to the background as expected and continue to communicate with the iOS app. What is the best way to move forward here. It almost feels like I am operating in a grey area with no real solution in place. Any assistance is greatly appreciated as we would like to follow all guidelines while producing a high quality experience for our users.
2
0
384
4w
Problem with connecting the workout data to a SwiftUI View.
Hello. I am building an app that shows my walk workouts and in the detail view I want to show the route I took while walking, similar to that of the Apple Fitness App. There is a problem though, I cannot seem to understand how to connect the @State property workoutLocations array that would be used to draw the route on the map with what I get from the query. The task does successfully fetches the data but then when I try to use it later in a do-catch block nothing happens. What am I missing here? import SwiftUI import MapKit import HealthKit struct DetailView: View { @Environment(HealthKitManager.self) var healthKitManager let workout: HKWorkout @State private var workoutLocations: [CLLocation] = [] var body: some View { ScrollView { //... } .task { guard let store = self.healthKitManager.healthStore else { fatalError("healthStore is nil. App is in invalid state.") } let walkingObjectQuery = HKQuery.predicateForObjects(from: workout) let routeQuery = HKAnchoredObjectQueryDescriptor(predicates: [.workoutRoute(walkingObjectQuery)], anchor: nil) let queryResults = routeQuery.results(for: store) let task = Task { var workoutRouteLocations: [CLLocation] = [] for try await result in queryResults { let routeSamples = result.addedSamples for routeSample in routeSamples { let routeQueryDescriptor = HKWorkoutRouteQueryDescriptor(routeSample) let locations = routeQueryDescriptor.results(for: store) for try await location in locations { workoutRouteLocations.append(location) print(workoutRouteLocations.count) // this prints out the number of locations in the sample. } } } return workoutRouteLocations } do { print(try await task.value.count) // this prints nothing. Therefore if I try to update workoutLocations array from here it would do nothing as well // workoutLocations = try await task.value therefore does nothing and the array just doesn't get populated with the results of the task } catch { print(error) } } } }
2
0
396
Jan ’25
Workouts fail to register on Fitness activity rings
Hello, My app syncs workout data from a third-party device and records workouts with HealthKit as follows: let builder = HKWorkoutBuilder(healthStore: healthStore, configuration: hkConf, device: hkDevice) try await builder.beginCollection(at: startDate) try await builder.addSamples(samples) try await builder.endCollection(at: endDate) let workout = try await builder.finishWorkout() let workoutRouteBuilder = HKWorkoutRouteBuilder(healthStore: healthStore, device: hkDevice) try await workoutRouteBuilder.insertRouteData(filteredLocations) try await workoutRouteBuilder.finishRoute(with: workout, metadata: nil) However, I’m encountering two issues: The workouts appear in Apple Fitness but do not contribute to the activity rings. The workout includes a route (visible in the raw workout data in Apple Health) but does not display on Apple Fitness. Is there any way to fix this? I’d appreciate any suggestions you might have. __
2
0
378
Jan ’25
Is sleep analysis data available in Smart Alarms?
I am working on a Smart Alarm app for Watch OS. When testing on an Series 10 watch, I am successfully able to read heart rate data in the ExtendedRuntimeSession. However, although the calls succeed, the sleep analysis data is all 0. The app successfully gets authorization for: [HKQuantityType(.heartRate), HKObjectType.categoryType(forIdentifier: .sleepAnalysis)!] I have read that sleep data is not available for less than an hour time period. The Smart Alarm extended session has a 30 minute limit. Does that mean it is not possible to read sleep analysis data in a Smart Alarm extended session? Thank you!
5
0
466
Jan ’25
Can I use an HKQueryAnchor across multiple devices?
Hello, I am currently working on an app that uses HealthKit to sync health data to a backend server that performs analysis on this data. I am keeping track of the synced data with the HKQueryAnchor I receive for each query I make. I want to address an edge case: if a user has multiple devices running the app, would it make sense to store the anchor on my backend? This would ensure that other instances of the app do not sync data that has already been synced from another device. Thank you for your help!
1
0
400
Jan ’25
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
415
Jan ’25
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
421
Jan ’25
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
502
Jan ’25
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
607
Jan ’25
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
259
Jan ’25
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
550
Jan ’25
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
542
Jan ’25
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
494
Jan ’25