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

Post

Replies

Boosts

Views

Activity

Walking/Running Distance not included in daily total
Hi, I have an iPhone/watch app that measures walking/running distance. It starts a workout session records data successfully into healthkit and then ends the workout session. I can see the data in the Health app from my app and it all appears to be correct. The issue I'm having is that the Health app doesn't use my app's data in its total distance for the day. For example, I can add 1 mile of fake data (I know that's not allowed per policy) for testing and it gets successfully added but not used in the total. The health app is only using distances collected by the watch and the phone for calculating the total distance for the day and is ignoring the distance provided by my app. What could I be missing?
2
0
195
2d
HKHealthStore().execute(query) will block main thread
HKHealthStore().execute(query) run in main thread it cost 3.5s here is my code print("execute begin:(Date().timeIntervalSince1970)") HKHealthStore().execute(query) print("execute end:(Date().timeIntervalSince1970)") query.predicate like this (startDate >= CAST(0.000000, "NSDate") AND endDate < CAST(0.100000, "NSDate") AND startDate < CAST(0.100000, "NSDate")) OR (startDate >= CAST(60.000000, "NSDate") AND endDate < CAST(60.100000, "NSDate") AND startDate < CAST(60.100000, "NSDate")) OR (startDate >= CAST(120.000000, "NSDate") AND endDate < CAST(120.100000, "NSDate") AND startDate < CAST(120.100000, "NSDate")) OR (startDate >= CAST(180.000000, "NSDate") AND endDate < CAST(180.100000, "NSDate") AND startDate < CAST(180.100000, "NSDate")) OR (startDate >= CAST(240.000000, "NSDate") AND endDate < CAST(240.100000, "NSDate") AND startDate < CAST(240.100000, "NSDate")) OR (startDate >= CAST(300.000000, "NSDate") AND endDate < CAST(300.100000, "NSDate") AND startDate < CAST(300.100000, "NSDate")) OR (startDate >= CAST(360.000000, "NSDate") AND endDate < CAST(360.100000, "NSDate") AND startDate < CAST(360.100000, "NSDate")) OR (startDate >= CAST(420.000000, "NSDate") AND endDate < CAST(420.100000, "NSDate") AND startDate < CAST(420.100000, "NSDate")) OR (startDate >= CAST(480.000000, "NSDate") AND endDate < CAST(480.100000, "NSDate") AND startDate < CAST(480.100000, "NSDate")) OR (startDate >= CAST(540.000000, "NSDate") AND endDate < CAST(540.100000, "NSDate") AND startDate < CAST(540.100000, "NSDate")) OR (startDate >= CAST(600.000000, "NSDate") AND endDate < CAST(600.100000, "NSDate") AND startDate < CAST(600.100000, "NSDate")) OR (startDate >= CAST(660.000000, "NSDate") AND endDate < CAST(660.100000, "NSDate") AND startDate < CAST(660.100000, "NSDate")) OR (startDate >= CAST(720.000000, "NSDate") AND endDate < CAST(720.100000, "NSDate") AND startDate < CAST(720.100000, "NSDate")) OR (startDate >= CAST(780.000000, "NSDate") AND endDate < CAST(780.100000, "NSDate") AND startDate < CAST(780.100000, "NSDate")) OR (startDate >= CAST(840.000000, "NSDate") AND endDate < CAST(840.100000, "NSDate") AND startDate < CAST(840.100000, "NSDate")) OR (startDate >= CAST(900.000000, "NSDate") AND endDate < CAST(900.100000, "NSDate") AND startDate < CAST(900.100000, "NSDate")) OR (startDate >= CAST(960.000000, "NSDate") AND endDate < CAST(960.100000, "NSDate") AND startDate < CAST(960.100000, "NSDate")) OR (startDate >= CAST(1020.000000, "NSDate") AND endDate < CAST(1020.100000, "NSDate") AND startDate < CAST(1020.100000, "NSDate")) OR (startDate >= CAST(1080.000000, "NSDate") AND endDate < CAST(1080.100000, "NSDate") AND startDate < CAST(1080.100000, "NSDate")) OR (startDate >= CAST(1140.000000, "NSDate") AND endDate < CAST(1140.100000, "NSDate") AND startDate < CAST(1140.100000, "NSDate")) OR (startDate >= CAST(1200.000000, "NSDate") AND endDate < CAST(1200.100000, "NSDate") AND startDate < CAST(1200.100000, "NSDate")) OR (startDate >= CAST(1260.000000, "NSDate") AND endDate < CAST(1260.100000, "NSDate") AND startDate < CAST(1260.100000, "NSDate")) OR (startDate >= CAST(1320.000000, "NSDate") AND endDate < CAST(1320.100000, "NSDate") AND startDate < CAST(1320.100000, "NSDate")) OR (startDate >= CAST(1380.000000, "NSDate") AND endDate < CAST(1380.100000, "NSDate") AND startDate < CAST(1380.100000, "NSDate")) OR (startDate >= CAST(1440.000000, "NSDate") AND endDate < CAST(1440.100000, "NSDate") AND startDate < CAST(1440.100000, "NSDate")) OR (startDate >= CAST(1500.000000, "NSDate") AND endDate < CAST(1500.100000, "NSDate") AND startDate < CAST( Log execute begin:1739958803.531026 execute end:1739958807.0448961
3
0
139
2d
Workout Types to be Added to Apple Watch
Dear Apple Developers, Could you kindly add the two following workout types to your Apple Watch? There are large communities that participate in both of these activities globally. Rucking workout option. goruck.com TRX suspension trainer option. trxtraining.com Thank you for your consideration. This addition will make many people happy.
1
0
142
3w
App's domain being blocked/rerouted by Apple
I have a strange situation and I'm not sure where else to post this. Our app's domain (or at least its API hostname in the domain) resolves to something different only inside of Apple's network. I was able to get an Apple employee to verify this by resolving the API hostname while on Apple's corporate network and it resolves to an IP that is in Apple's 17.0.0.0/8 network, but everywhere else resolves to the normal IPs. Our domain's DNS is provided by Cloudflare and they are not doing anything special for Apple's network. This is causing problems during App Review because the app is trying to reach our API to log in and instead is being routed to an IP in Apple's network, so it fails SSL validation and presents an error dialog. App Review is then claiming our app doesn't work and rejecting it. This is an app that has been in the App Store for over a decade and gone through countless app reviews. App Review was of no help resolving this and I don't know where else to turn. How can I find out why our domain is being rerouted inside of Apple and get this fixed?
3
0
271
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
315
3w
Can't create energy goals in WorkoutKit
I can create WorkoutGoals of all kinds except .energy, but I can't find any indication of the conditions under which energy goals can be used. No matter what I try, the response from supportsGoal is always false e.g. CustomWorkout.supportsGoal(.energy(10, .kilojoules), activity: .running, location: .outdoor) CustomWorkout.supportsGoal(.energy(10, .calories), activity: .cycling, location: .outdoor) CustomWorkout.supportsGoal(.energy(10, .kilocalories), activity: .running, location: .outdoor) For any combination I've tried, I get Not supported due to unsupportedGoal Has anybody managed to successfully create energy goals?
2
0
329
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
323
3w
Apple Watch Ultra 2 having issues with heart rate measurements
I am using a new Apple Watch Ultra 2 (MX5R3LW/A) running WatchOS 11.3 (22S553). I noticed that the watch often misses heart measurements during meaningfully long segments of exercise sessions. This has been bugging me for a while and today I read an article that described perfectly, and much better than I could, what I am experiencing. Here is the article: https://apple.news/AK_QJyoLaQ1eaeySWHlkLPw Is this a known issue that is being worked? Thanks.
1
0
335
3w
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
322
4w
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
405
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
340
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
354
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
439
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
546
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
236
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
491
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
431
Dec ’24
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
458
Dec ’24