Health and Fitness

RSS for tag

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

Posts under Health and Fitness tag

81 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Recording a HeartbeatSeries
I need to be able to create and store a HeartbeatSeries for a given time-period from an Apple Watch, to then retrieve that data from HealthKit to be processed. I have working code which allows me to begin a workout session, which is being used to determine how long a session has been running for. I also have working code for retrieving HeartbeatSeries data from HealthKit. The issue is that no HeartbeatSeries data is being stored into HealthKit as a result of the workout session running. Whether that session is running for as little as 30 seconds or as long as 20 minutes, nothing is stored. However, when I use the the Apple "Meditation" app (formerly known as "Breathe"), I can query HealthKit afterwards and retrieve a list of individual heartbeat timings during that 2 minute period. Therefore, it IS possible to store a HeartbeatSeries from within an app on the Apple Watch. What I would like to know is, how can I use the pulse sensor built-in to the Apple Watch to be able to record a HeartbeatSeries similar to how the Meditation app does it.
3
0
44
1d
Sleep Samples sum off by 2 minutes
Hi everyone! I'm trying to get the total sleep time for a given day, but users report that there's a difference between what my app reports and what the Apple Health app reports. In particular, we're off by 2 minutes less on average. What we're doing is: Get all the samples that are either core, deep, rem or unspecified Cut-off time at 3 PM previous day Merge overlapping intervals Add all the remaining intervals For debugging purposes I'm storing and sending all the raw samples to a server, and I have run tests and I don't find anything wrong. It looks like the number we come up with is correct according to our own rules. I wonder, how is Apple adding up all the samples to arrive at a number that's slightly off to our number. Any insight would be appreciated. Thanks.
5
0
133
5d
HKAnchoredObjectQuery Stops Receiving Updates
I implemented this to receive updates for specific data types and keep the latest daily information up to date. However, for some reason, it only works for a while before stopping completely. Background Delivery internal func backgroundDeliveryForReadTypes(enable: Bool, types: Set<HKQuantityType>) async { do { if enable { try await statusForAuthorizationRequest(toWrite: [], toRead: types) for type in types { try await healthStore.enableBackgroundDelivery(for: type, frequency: .daily) } } else { for type in types { try await healthStore.disableBackgroundDelivery(for: type) } } } catch { debugPrint("Error enabling background delivery: \(error.localizedDescription)") } } HKQueryAnchor internal var walkingActivityQueryAnchor: HKQueryAnchor? { get { if let anchorData = UserDefaults.standard.data(forKey: "walkingActivityAnchor") { return try? NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: anchorData) } return nil } set { if let newAnchor = newValue { let anchorData = try? NSKeyedArchiver.archivedData(withRootObject: newAnchor, requiringSecureCoding: true) UserDefaults.standard.set(anchorData, forKey: "walkingActivityAnchor") } else { UserDefaults.standard.removeObject(forKey: "walkingActivityAnchor") } } } HKAnchoredObjectQuery internal func observeWalkingActivityInBackground( _ start: Bool, toRead: Set<HKQuantityType>, completion: @escaping @Sendable (Result<WalkingActivityData?, Error>) -> Void ) { if start { guard (walkingActivityQuery == nil) else { return } let predicate = getPredicate(date: Date()) let queryDescriptors = toRead.map { HKQueryDescriptor(sampleType: $0, predicate: predicate) } let handleSamples: @Sendable (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = { [weak self] _, samples, _, newAnchor, error in guard let self = self else { return } if let error = error { completion(.failure(error)) return } guard let samples = samples, !samples.isEmpty else { completion(.success(nil)) return } Task { self.walkingActivityQueryAnchor = newAnchor let activity = await self.getWalkingActivity(date: Date()) completion(.success(activity)) } } let query = HKAnchoredObjectQuery( queryDescriptors: queryDescriptors, anchor: walkingActivityQueryAnchor, limit: HKObjectQueryNoLimit, resultsHandler: handleSamples ) query.updateHandler = handleSamples healthStore.execute(query) walkingActivityQuery = query } else { if let query = walkingActivityQuery { healthStore.stop(query) walkingActivityQuery = nil } } } WalkingActivityData private func getWalkingActivity(date: Date) async -> WalkingActivityData { async let averageHeartRate = try await self.getAverageHeartRate(date: date) async let steps = try self.getStepCount(date: date) async let durationMinutes = try self.getTotalDurationInMinutes(date: date) async let distanceMeters = try self.getDistanceWalkingRunning(date: date, unit: .meter()) async let activeCalories = try self.getActiveEnergyBurned(date: date) return await WalkingActivityData( date: date, steps: try? steps, activeCalories: try? activeCalories, distanceMeters: try? distanceMeters, durationMinutes: try? durationMinutes, averageHeartRate: try? averageHeartRate ) } Example of getAverageHeartRate func getAverageHeartRate(date: Date) async throws -> Double? { let type = HKQuantityType(.heartRate) _ = try checkAuthorizationStatus(for: type) guard let heartRate = try await getDescriptor( date: date, type: type, options: .discreteAverage ).result(for: healthStore) .statistics(for: date)? .averageQuantity()?.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minute())) else { return nil } return Double(String(format: "%.2f", heartRate)) ?? 0.0 } Descriptor & predicate internal func getPredicate(startDate: Date, endDate: Date) -> NSCompoundPredicate { let predicateForSamples = HKQuery.predicateForSamples(withStart: startDate, end: endDate) let excludeManual = NSPredicate(format: "metadata.%K != YES", HKMetadataKeyWasUserEntered) return NSCompoundPredicate(andPredicateWithSubpredicates: [predicateForSamples, excludeManual]) } internal func getDescriptor(startDate: Date, endDate: Date, type: HKQuantityType, options: HKStatisticsOptions) -> HKStatisticsCollectionQueryDescriptor { let calendar = Calendar(identifier: .gregorian) let anchorDate = calendar.date(bySetting: .hour, value: 0, of: startDate)! var interval = DateComponents() interval.day = 1 return HKStatisticsCollectionQueryDescriptor( predicate: HKSamplePredicate.quantitySample(type: type, predicate: getPredicate(startDate: startDate, endDate: endDate)), options: options, anchorDate: anchorDate, intervalComponents: interval ) } Implementation public func observeWalkingActivityInBackground(_ start: Bool, toRead: Set<HKQuantityType>, memberID: String) { observeWalkingActivityInBackground(start, toRead: toRead) { [weak self] result in guard let self = self else { return } } }
1
0
138
2w
How to Save Heart Rate in HKCategoryTypeIdentifier.mindfulSession
I’m trying to associate heart rate (HR) data with a mindfulness session (HKCategoryTypeIdentifier.mindfulSession) in HealthKit, but I can’t find any documentation on how to do this. I’ve seen third-party apps (like Medito) successfully log HR within Mindful Minutes, even when the session takes place on an iPhone (not an Apple Watch). However, when I try saving HR in the metadata, it does not appear in the Health app's Mindful Minutes section. Code snippet: func logMindfulnessSession(start: Bool, heartRate: Double? = nil) { let mindfulType = HKCategoryType.categoryType(forIdentifier: .mindfulSession)! let now = Date() let endTime = now.addingTimeInterval(Double(selectedDuration)) var metadata: [String: Any]? = nil if let hr = heartRate { let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute()) let hrQuantity = HKQuantity(unit: heartRateUnit, doubleValue: hr) metadata = ["heartRate": hrQuantity] // ❓ Is there a correct key for HR? } let sample = HKCategorySample( type: mindfulType, value: 0, start: now, end: endTime, metadata: metadata ) healthStore.save(sample) { success, error in if let error = error { print("HealthKit session save error: \(error.localizedDescription)") } else { print("Mindfulness session saved successfully.") if let hr = heartRate { print("Saved with HR: \(hr) BPM") } } } } Questions: What is the correct metadata key for associating heart rate with a mindful session? Does HealthKit require a specific format (e.g., HKQuantitySample) for HR? 0 Are there additional permissions needed to allow HR to appear in Mindful Minutes? Does HR need to be stored separately in HKQuantityTypeIdentifier.heartRate, and if so, how do third-party apps ensure it appears in the same entry as the mindful session? thank you!
1
0
419
3w
Integrating Apple Fitness+ Workouts – How to Retrieve Metadata?
Platform & Version: iOS Version: 18.3.1 Development Environment: Xcode 16.2, macOS 14.6.1 Description of the Issue: We're exploring ways to better integrate Apple Fitness+ workouts into our app. We've noticed that some third-party apps, such as Strava and HealthFit, now display Fitness+ workout details, including the title, trainer, and an image. I’ve been investigating how this is possible, and the only relevant change I’ve found is that HKMetadataKeyAppleFitnessPlusCatalogIdentifier is now being set for Fitness+ workouts. However, I can’t find any public API or official documentation that explains how to use these identifiers to retrieve the associated workout details. Question: Is there an official API available to fetch metadata for Fitness+ workouts using these identifiers? Or are these third-party apps potentially accessing private APIs? If no API exists, is the only option to create a manual mapping of these identifiers—something that seems impractical given the constantly evolving Fitness+ workout catalog? Any guidance on this would be greatly appreciated. Thanks!
3
0
542
4w
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
677
Jan ’25
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
747
Jan ’25
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
754
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
711
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
754
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
867
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
891
Jan ’25
Inquiry About Background Permission Issue in My App
I am writing to address a concern regarding the background permission functionality in my app, which is critical for ensuring user safety as they navigate various terrains. This feature also enables users to smoothly record their navigation tracks for review after their activities. Recently, I've noticed that this functionality is not working as seamlessly as before. Additionally, I observed that the app is not categorized under 'health and fitness'—could reclassifying it improve background activity? Before I delve into a detailed code review, I wanted to check if this issue might be related to sync or settings on the App Store side, such as permission configurations, app updates, or other related factors. Or, is it more likely an issue stemming from the app’s codebase?
1
0
403
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
835
Jan ’25
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
872
Jan ’25
Is Using EAS Update (OTA) Compliant with Apple App Store Policies for a Health App?
Hi everyone, I’m developing a health-related mobile app and considering using EAS Update to deliver over-the-air (OTA) updates for JavaScript code and assets. Before implementing this, I want to ensure that this approach complies with Apple App Store policies, especially given the sensitivity of health-related apps. Here are my concerns: Does using EAS Update (OTA) align with Apple’s guidelines regarding app updates and dynamic behavior changes? Are there specific rules or restrictions for health apps using OTA updates that I should be cautious of? Could this approach be flagged as violating Apple’s policies on app integrity, especially those requiring updates to go through the App Store review process? I’d greatly appreciate any insights, advice, or references to Apple’s official documentation regarding OTA updates for apps distributed through the App Store. Thanks in advance for your help!
0
0
402
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
895
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
865
Dec ’24