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

Health & Fitness

RSS for tag

Explore the technical aspects of health and fitness features, including sensor data acquisition, health data processing, and integration with the HealthKit framework.

Health & Fitness Documentation

Posts under Health & Fitness subtopic

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
internal healthkit error: "Unable to invalidate interval: no data source avallable"
we are seeing what appears to be an internal healthkit error appearing in our app.  not sure if it's connected, but we've mostly seen it reported on devices running ios 16.  even though our app's primary language is japanese, and in all reported occurrences the app was running in japanese, the error message itself appears in english.  searching the error string on the web yields surprisingly few results (including only two mentions on this forum that i could find, neither of which seemed relevant).  this would seem to suggest that it's coming from something deep inside healthkit, since the error message is not localized.  in all reported cases, the user had recently upgraded to a new iphone.  in most cases, the problem only occurs on the new device even though everything had been working correctly prior to the upgrade.  the error occurs when the app is unable to read step count data from healthkit. we have confirmed that the app has been granted access permissions to all health data via os settings.  we've also tried having the user toggling those settings off, then back on, rebooting the device, deleting and reinstalling the app, etc., to no avail. the error message is "Unable to invalidate interval: no data source avallable." we'd appreciate it if anyone can shed more light on this issue. thanks!
4
3
1.7k
Nov ’22
HealthKit permission sheet appears every time for some users - bug?
The HealthKit permission sheet is showing up every time the app opens for a few users of my app. It doesn't matter what action they take in the sheet. I have had them try toggling the permissions from the HealthKit system settings but that did not happen to fix the problem. Has anyone experienced this problem or know a fix? Its affecting a few users of my app. I haven't been able to find what in my code could be doing this, I suspect its a bug on HealthKit's side for specific users. I can't find anyone reporting this problem elsewhere so I have to assume its my fault, but the docs clearly state that the permission sheet will only be presented once.
8
9
2.0k
Feb ’24
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
HKObserverQuery not working in background
I'm developing a single target watchOS app that obtains HealthKit information. I have the "Background Delivery" option checked under "Signing & Capabilities" for the watch target. The app does HKObserverQueries in the foreground that work as I would expect. But when I click the Digital Crown to return to clock face, the HKObserverQuery activity stops. I'm using Xcode 15.4, on Mac 14.5 and a Apple Watch Series 4 running 10.5.
3
0
704
Jun ’24
Get distance from Fitness Machine Device
I think I know the answer to this question, but is there any way to 'manually' add distance to a SingleGoalWorkout? I.e., I want to make a SingleGoalWorkout with a location set to .indoor, and then add any meters the user has covered from a BLE Fitness Machine Device (exercise bike, indoor rower etc.) towards the workout goal. Is this possible?
0
0
572
Jun ’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
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
Scale app for coffee and small dishes
I just want to make my V60 coffee I found out that my electronic scale ran out of battery and there is no charger in my work location and I also work on a remote area nearest city about 100 km so, I grab my iPhone to find out is there any app can scale my coffee grams and water mills by putting coffee bin above the iPhone for measuring it’s weight. The answer is no, there are no apps for measuring weight of coffee bens and water droplets to make V60 coffee. Still I have made my coffee perfectly from my experience. I am writing this post just to have scale app at my iPhone and also if I can get some money it is good because no one can say no for the money
4
0
655
Jul ’24
Resting Heart Rate - Individual readings?
I receive multiple resting heart rate readings throughout the day. I understand these readings are taken during the day while sedentary. However, if I query for: HKQuantityType.quantityType(forIdentifier: .restingHeartRate) I only receive ONE sample for the day, even though throughout the day multiple samples are observed. This is confirmed by looking at the Apple Health app and seeing only one recorded resting heart rate each day. Is there a way to get the individual resting heart rate readings for the .restingHeartRate type or am I stuck with querying the raw heart rate data for sedentary values (which don't always match Apples reported rhr)?
1
0
1.2k
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
Xcode 15 and CocoaPods — building for iOS failed with Ld error
** BUILD FAILED ** The following build commands failed: Ld /Users/siddesh/Library/Developer/Xcode/DerivedData/App-ddpkkzvberburtewkcvoihnirgjh/Build/Intermediates.noindex/Pods.build/Release-iphonesimulator/Logging.build/Objects-normal/x86_64/Binary/Logging normal x86_64 (in target 'Logging' from project 'Pods') (1 failure) Testing with xcodebuild. -> mySDK_Staging (8.8.0) - WARN | attributes: Missing required attribute license. - WARN | license: Missing license type. - WARN | source: Git SSH URLs will NOT work for people behind firewalls configured to only allow HTTP, therefore HTTPS is preferred. - WARN | [iOS] license: Unable to find a license file - ERROR | [iOS] xcodebuild: Returned an unsuccessful exit code. - NOTE | xcodebuild: note: Using codesigning identity override: - - NOTE | [iOS] xcodebuild: note: Building targets in dependency order - NOTE | [iOS] xcodebuild: note: Target dependency graph (20 targets)
0
0
368
Jul ’24
Linker errors when building with Xcode 12 and CocoaPods — building for iOS
** BUILD FAILED ** The following build commands failed: Ld /Users/siddesh/Library/Developer/Xcode/DerivedData/App-ddpkkzvberburtewkcvoihnirgjh/Build/Intermediates.noindex/Pods.build/Release-iphonesimulator/Logging.build/Objects-normal/x86_64/Binary/Logging normal x86_64 (in target 'Logging' from project 'Pods') (1 failure) Testing with xcodebuild. -> mySDK_Staging (8.8.0) - WARN | attributes: Missing required attribute license. - WARN | license: Missing license type. - WARN | source: Git SSH URLs will NOT work for people behind firewalls configured to only allow HTTP, therefore HTTPS is preferred. - WARN | [iOS] license: Unable to find a license file - ERROR | [iOS] xcodebuild: Returned an unsuccessful exit code. - NOTE | xcodebuild: note: Using codesigning identity override: - - NOTE | [iOS] xcodebuild: note: Building targets in dependency order - NOTE | [iOS] xcodebuild: note: Target dependency graph (20 targets)
0
0
358
Jul ’24
Linker errors when building with Xcode 15 and CocoaPods — building for iOS
** BUILD FAILED ** The following build commands failed: Ld /Users/siddesh/Library/Developer/Xcode/DerivedData/App-ddpkkzvberburtewkcvoihnirgjh/Build/Intermediates.noindex/Pods.build/Release-iphonesimulator/Logging.build/Objects-normal/x86_64/Binary/Logging normal x86_64 (in target 'Logging' from project 'Pods') (1 failure) Testing with xcodebuild. -> mySDK_Staging (8.8.0) - WARN | attributes: Missing required attribute license. - WARN | license: Missing license type. - WARN | source: Git SSH URLs will NOT work for people behind firewalls configured to only allow HTTP, therefore HTTPS is preferred. - WARN | [iOS] license: Unable to find a license file - ERROR | [iOS] xcodebuild: Returned an unsuccessful exit code. - NOTE | xcodebuild: note: Using codesigning identity override: - - NOTE | [iOS] xcodebuild: note: Building targets in dependency order - NOTE | [iOS] xcodebuild: note: Target dependency graph (20 targets)
0
0
377
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
CMBatchedSensorManager referenced on a iOS 15 device
We have an app that takes data from the accelerometer of the iPhone and watchOS. Some updates ago we included the high-frequency accelerometer for the watchOS with the CMBatchedSensorManager framework. We didn't test our app on iOS 16 or 15 devices, where that framework is unavailable, because the update was just for watchOS. We refer to that class just on a shared class, and was wrapped with an #if os(watchOS) condition. In our iPhone app, we import the CoreMotion framework but CMBatchedSensorManager is not used. Now, when you run the app on a device with iOS 15 you find this issue: dyld[17071]: Symbol not found: (OBJC_CLASS$_CMBatchedSensorManager) Referenced from: '/private/var/containers/Bundle/Application/C3CC754F-1674-4CBD-AD83-93229DDCF38D/Spleeft.app/Spleeft' Expected in: '/System/Library/Frameworks/CoreMotion.framework/CoreMotion' We need a solution to keep running our app on devices with iOS 15.0
2
0
687
Aug ’24