Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Use HealthKit to enable your iOS and watchOS apps to work with the Apple Health app.

All subtopics
Posts under Health and Fitness topic

Post

Replies

Boosts

Views

Activity

HKAnchoredObjectQuery updateHandler stops working with error
Hi! I am using the HKAnchoredObjectQuery to first get a snapshot of the initial results, and then trigger an updateHandler. I need to handle the initial results and the updates separately, which is why I implemented two completions. When I test the code, it works for a while. New and deleted samples trigger the updateHandler. However, after a while there appears an error: [connection] nw_read_request_report [C2] Receive failed with error "Software caused connection abort" Followingly, the updateHandler will stop getting triggered when I add updates in Apple health. Anyone have experience with this? func getMostRecentSample(for sampleType: HKSampleType, anchorKey: String, completion: @escaping (HKQuantitySample?, Error?) -> Swift.Void, updateHandler: @escaping (HKQuantitySample, Error?) -> Swift.Void) {     // If it is the first initialization, anchor is passed as nil     var anchor: HKQueryAnchor? = nil // Check for previous saved anchor in userdefaults     if UserDefaults.standard.object(forKey: anchorKey) != nil {       let data = UserDefaults.standard.object(forKey: anchorKey) as! Data       do {         guard let newAnchor = try NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: data) else {           print("Could not parse anchor to HKQueryAnchor type")           return         }         anchor = newAnchor       } catch {         print("Error retreiving anchor from UserDefaults")       }     }     let query = HKAnchoredObjectQuery(type: sampleType,                      predicate: nil,                      anchor: anchor,                      limit: HKObjectQueryNoLimit                       ) { (query, samplesOrNil, _, newAnchor, errorOrNil) in       guard let samples = samplesOrNil as? [HKQuantitySample] else {         fatalError("*** An error occurred during the initial query: \(errorOrNil!.localizedDescription) ***")       }       if let anchor = newAnchor {         do {           let data = try NSKeyedArchiver.archivedData(withRootObject: anchor as Any, requiringSecureCoding: false)           UserDefaults.standard.set(data, forKey: anchorKey)         } catch {           print("Error retreiving anchor from UserDefaults")         }       }       completion(samples.last, nil)     }           // Setting up long-running query     query.updateHandler = { (query, samplesOrNil, _, newAnchor, errorOrNil) in       guard let samples = samplesOrNil as? [HKQuantitySample] else {         fatalError("*** An error occurred during an update: \(errorOrNil!.localizedDescription) ***")       }       if let anchor = newAnchor {         do {           let data = try NSKeyedArchiver.archivedData(withRootObject: anchor as Any, requiringSecureCoding: false)           UserDefaults.standard.set(data, forKey: anchorKey)         } catch {           print("Error retreiving anchor from UserDefaults")         }       }       if let sample = samples.last {         updateHandler(sample, nil)       }     }     self.healthStore.execute(query)   }
2
0
1.1k
Oct ’22
How to add "Estimated Time in Each Heart Rate Zone" info to my custom HKWorkout when viewed in Apple Fitness app?
Hello, I’m currently developing a fitness app for watchOS that lets a user to manually set a desired heart rate target zone (enter numbers representing the lower and upper boundaries) and start a workout (right now it’s only “Other” type). After that my app monitors user’s heart rate and alerts them when they’re out of zone. When user ends the workout, the info about this workout appears on “Fitness” iOS app, and user can see the workout data like Workout Time, Active and Total Calories, Avg. Heart Rate. Also user can see Heart Rate chart with info how their heart rate was changing during a workout (see the Figure 1). Now to the question. When user clicks “Show More” button above the Heart Rate chart, they can see the same Heart Rate chart and another one, with Post-Workout Heart Rate (see the Figure 2). But there is no “Estimated time in each heart rate zone” as one can see in the workout’s details that were recorded from Apple’s workout (watchOS “Workout” app, for a workout of “Other” type as well). Please see the Figure 3. The question is: is it possible to add “Estimated time in each heart rate zone” to workout recorded via my third-party app so it would look like on the Figure 3 in "Fitness" iOS app, and if it's possible, what steps should I undertake to implement this ? Thanks in advance! I posted the screenshots in the replies to the post, because otherwise I was not able to submit a post ("sensitive language" warning, I suspect it's because of the ids in the attached screenshot's urls)
2
0
1.1k
May ’24
Writing Workout Data into HealthKit
Hello, I am writing workout data into HealthKit using the HKWorkoutBuilder API for specific types of workouts (e.g. Cycling) in particular various time series data for power, speed, etc.. but I am unable to see the average values for these quantities on the workout summary page in the Apple Fitness app ? (I am only able to see the graph data in the show more / workout details) anything specific to be done in order to have the data shown in the main summary ?
1
0
643
Jul ’24
Request for Solution to Retrieve Step Count Data from Apple Health Kit for QSFA App in Background Mode
Dear Apple Team, QSFA app belongs to the Ministry of Sports and Youth in Qatar and there's a feature which will get the step count from the Apple health kit. Our issue that while the app is closed or on the background, we are not getting the steps count for the users and we need the steps data to keep sending notifications based on the steps as motivations to the users to keep walking and do sport. Please give us a suggestion or solution on how we can retrieve the steps data as we have limitations on this.
0
0
430
Jul ’24
Watch not detecting stands
During WatchOS 10 dev betas and now into 11 dev betas, I am still seeing were stands are not being detected. What I do not know is if the steps are detected. But here is the situation. Today: I was going on some wiring outside and in the basement. I was clearly up and moving around for over an hour. I can see on my camera's I went outside at 15:50, came back in at 16:18. Then went to my basement and was working down there from 16:19 until 16:30. After that cleaned up my mess. So I was up and down stairs and without a doubt standing. At 16:50 I got the reminder to stand. Other cases: 1: I get home from work about XX:10 . I have to walk about 50 ft from my garage to my house, up stairs, take the dog out, make dinner, and finally get my chair to eat and at XX:50 I get the reminder. 2: I'm at work, I'm going to get lunch and I have to walk pretty far and again at XX:50 I get the reminder. This is very rare, but it has happened. Now, in a odd twist. I get up in the morning at XX:50, I have 10 steps to the bathroom, and I manage to get that hourly stand.
0
0
590
Jul ’24
Step Data Duplication Issue with Apple Health Integration
We are integrating Apple Health step data into our mobile application, Diyetkolik. However, we have received feedback from our users indicating that the step data appears to be significantly higher than expected. After conducting thorough research, we discovered that users who wear a smartwatch are experiencing step data duplication. Both the smartwatch and the phone's step data are being collected and combined, leading to inflated step counts in our application. We kindly request your assistance in addressing the following issues: How can we differentiate between step data from the smartwatch and the phone to avoid duplication? Are there best practices or specific APIs we should use to filter and manage step data more accurately? Can you provide guidance on how to implement a solution that ensures accurate step count data for users wearing multiple devices? We appreciate your support in resolving this matter to enhance the accuracy of our application and improve user experience.
1
0
1k
Jul ’24
Workout validation and Scheduler logic
Hey folks, a couple of questions regarding WorkoutKit: What happened to validation errors? They are mentioned in the WWDC23 video, but no longer are present in the API. It seems a fatal error is thrown if the workout fails validation (for example setting a negative distance in a workout goal). What is the logic of the WorkoutScheduler, if we try to add more workouts than is allowed? If the limit is 50, what happens when we try to add a 51st? Are workouts de-queued based on date or anything? API documentation is very sparse Do completed workouts and workouts with a scheduled date in the past stay in the WorkoutScheduler? Are we responsible for removing these? I guess my overall question regarding the WorkoutScheduler is, what are we responsible for managing and what is handled gracefully for us. None of these answers seem to be openly available, but if anyone know anecdotally or even better from the WorkoutKit team, I'd be very grateful! Thanks!
1
1
683
Jul ’24
Can my iOS app access live cycling workout session data from the workouts app on the apple watch
Hello, I am trying to build a features where I want to monitor a user's biking workout session metrics like the current speed, average speed and distance travelled. I want to get these metrics as the user is actively doing a workout session in the Workouts app of the apple watch. Is it possible? Or it is not possible to get data from an active workout session from the workouts app.
0
0
456
Jul ’24
Missing app icon in the Fitness app
My iOS app has a correctly configured HealthKit integration. It successfully delivers all samples and data to HealthKit. For every workout sent to HealthKit, I can see the duration, workout name, calories, and other details. However, the app icon is missing. My project uses the Single Size setting for the app icon in the XCAssets folder. The app is available in the App Store in some regions. What can I do to fix this issue? The problem persists regardless of whether the device is running iOS 17 or 18.
4
2
682
Aug ’24
watchOS 11 beta 5 - Problem workout duration wrong on automatically appearing widget
On watchOS 11 when starting a workout session a widget appears automatically on the smart stack showing the pause or resume button. It´s a great feature, but my problem is that the duration is not showed correctly because the prepare phase of the workout and the pause / resume events are not taken into account calculating the duration. In my project I don´t use the workout builder. I have made a sample project with workout builder and there the duration is shown correctly. It would be great if this automatically appearing widget would also show the time correctly in case the workout builder is not used (prepare phase and pause resume events considered, otherwise it looks like a bug). Is there any way to opt out of this automatically appearing widget or could this be fixed? Any comments from an Apple engineer on this?
1
0
555
Aug ’24
Health app iOS 18 Public Beta: Can't record Sleep Process with iPhone only (without wearable)
Hello! My sleep process isn't recorded with iPhone only (without wearable device) on iOS 18. On previous iOS versions it was recorded but now it doesn't work. I compare iOS 17 and iOS 18 Beta and I see the difference that in Full Schedule was deleted tumbler "Track Time in Bed with iPhone" that helped to track sleep process without wearable device (I found it here: Health app -> Browse -> Sleep -> Your schedule block and tap on "Full Schedule & Options" -> Scroll to the bottom). I didn't find any information from Apple about this changes in change log. And one more time: I don't use Apple Watch or any wearable device. Do you have any information about sleep tracking with iPhone only? Can I track sleep process only with iPhone?
0
1
1.1k
Aug ’24
Unable to fetch Water data from HealthKit
Hi All, I am posting this to get some help on fetching Water intake data from Health Kit. I have done (following a similar approach, and perfectly working) the fetch of the user weight, but for the water, somehow, I always receive back 0 samples. I went to the Health App, added few entries (in different days) for the water intake, under the food sections. Then, I use the following snippet to read the values, but I always have 0 values back. What I am doing wrong? let type = HKQuantityType(.dietaryWater) let samplePredicate = HKSamplePredicate.sample(type: type, predicate: nil) // Create the descriptor. let descriptor = HKSampleQueryDescriptor( predicates: [samplePredicate], sortDescriptors: [SortDescriptor(\.endDate, order: .reverse)]) let results = try await descriptor.result(for: hkHealthStore) The results variable is always 0 elements. What I am doing wrong? PS: The permissions are checked and correctly given for this: HKQuantityType(.dietaryWater)
1
0
563
Aug ’24
Apple Health `export.zip` doesn't include several important data points.
Heya, I'm currently building out my own application for tracking my health information, and I'm hoping to collect my historical data from Apple Health. Sadly, it would appear that certain things I wish to export don't appear in the export.xml file. Some of the things that I would expect to find in the export.xml file, that do not currently appear, are as follows: More data about my medications, currently I can only export a list of my medications, its not possible to export data such as when what medication was taken. Logged emotions; there is currently no support for this (that I can find). Would appreciate some insight into this.
1
0
701
Aug ’24
BGTaskScheduler with
I’m trying to use BGProcessingTaskRequest to fetch step data in the background and send it. However, when I combine BGProcessingTaskRequest, HKObserverQuery, and healthStore.enableBackgroundDelivery, the results sometimes return zero. When I don’t schedule the BGProcessingTaskRequest, the data retrieved using HKObserverQuery and HKSampleQueryDescriptor is correct. // Register Smart Walking Sync Task func registerSmartWalkingSync() { #if !targetEnvironment(simulator) BGTaskScheduler.shared.register(forTaskWithIdentifier: BGTaskIdentifier.smartwalking.rawValue, using: nil) { task in guard let task = task as? BGProcessingTask else { return } self.handleSmartWalkingSync(task: task) } #endif } func scheduleSmartWalkingSync(in seconds: TimeInterval? = nil, at date: Date? = nil) { let newRequest = BGProcessingTaskRequest(identifier: BGTaskIdentifier.smartwalking.rawValue) newRequest.requiresNetworkConnectivity = true newRequest.requiresExternalPower = false if let seconds = seconds { newRequest.earliestBeginDate = Date().addingTimeInterval(seconds) } else if let date = date { newRequest.earliestBeginDate = date } do { try BGTaskScheduler.shared.submit(newRequest) debugPrint("✅ [BGTasksManager] scheduled for Smart Walking Sync") } catch { FirebaseConnection.shared.recordException(error) debugPrint("❌ [BGTasksManager] error: \(error)") } } // Handle Smart Walking Sync Task func handleSmartWalkingSync(task: BGProcessingTask) { debugPrint("🔄 [BGTasksManager] sync \(task.identifier) sync started") scheduleSmartWalkingSync(in: SYNC_SMARTWALKING_TIME_INTERVAL) let queue = OperationQueue() let operation = HealthActivitiesOperation() operation.completionBlock = { Task { do { try await operation.sync() task.setTaskCompleted(success: !operation.isCancelled) debugPrint("✅ [BGTasksManager] sync \(task.identifier) completed successfully") } catch { FirebaseConnection.shared.recordException(error) task.setTaskCompleted(success: false) debugPrint("❌ [BGTasksManager] sync \(task.identifier) error: \(error)") } } } task.expirationHandler = { operation.cancel() } queue.addOperation(operation) } // MARK: - HealthKit Background Delivery internal func enableBackgroundDeliveryForAllTypes() async throws { for type in allTypes.filter({ type in type != HKQuantityType(.heartRate) }) { try await healthStore.enableBackgroundDelivery(for: type, frequency: .daily) } debugPrint("✅ [HealthKitManager] Enable Background Delivery") } internal func observeHealthKitQuery(predicate: NSPredicate?) async throws -> Set<HKSampleType> { let queryDescriptors: [HKQueryDescriptor] = allTypes .map { type in HKQueryDescriptor(sampleType: type, predicate: predicate) } return try await withCheckedThrowingContinuation { continuation in var hasResumed = false let query = HKObserverQuery(queryDescriptors: queryDescriptors) { query, updatedSampleTypes, completionHandler, error in if hasResumed { return } if let error = error { continuation.resume(throwing: error) } else { continuation.resume(returning: updatedSampleTypes ?? []) } hasResumed = true completionHandler() } healthStore.execute(query) } } internal func getHealthActivity(by date: Date, predicate: NSCompoundPredicate, sampleTypes: Set<HKSampleType>) async throws -> HealthActivityData { var data = HealthActivityData(steps: 0, calories: 0, distance: 0.0, distanceCycling: 0.0, totalDuration: 0, date: date, heartRate: nil) for sampleType in sampleTypes { guard let quantityType = sampleType as? HKQuantityType else { continue } switch quantityType { case HKQuantityType(.stepCount): let stepCount = try await getDescriptor( date: date, type: quantityType ).result(for: healthStore) .statistics(for: date)?.sumQuantity()?.doubleValue(for: HKUnit.count()) data.steps = stepCount ?? 0.0 // Calculate total duration using HKSampleQueryDescriptor let totalDurationDescriptor = HKSampleQueryDescriptor( predicates: [.quantitySample(type: quantityType, predicate: predicate)], sortDescriptors: [SortDescriptor(\.endDate, order: .reverse)] ) let stepSamples = try await totalDurationDescriptor.result(for: healthStore) data.totalDuration += stepSamples .reduce(0) { $0 + $1.endDate.timeIntervalSince($1.startDate) } / 60.0 default: debugPrint("Unknown quantity type") } } return data }
2
0
642
Aug ’24