I have FB12696743 open since July 21, 2023 and this happened again today.
I get home at approx 10 mins after the hour, walk appox 50 ft across my yard, up 5 steps into my house, let the dog out and pace on my deck watching the dog, go back in the house walk around the kitchen while preparing dinner. A total of about 200 ft. I sit down about 35 past the hour and start to eat and at 10 mins to the next our and I get the reminder to stand.
On the other side I wake up at 5 mins to hour. Walk 8 steps to the bathroom and successfully achieve the stand for that hour.
WHY!?!?!? 😁🤣
Use HealthKit to enable your iOS and watchOS apps to work with the Apple Health app.
Post
Replies
Boosts
Views
Activity
Hello everyone,
I hope you’re all doing well. I’m not a developer, but I have an idea for an iOS app that I’d love to get your thoughts on. I wanted to share it here to gather feedback from this knowledgeable community and to learn from your expertise.
Idea Overview: Real-Time AI Running Coach for iOS
The concept is an iOS application that provides personalized, real-time running coaching by leveraging on-device data sources and Apple’s latest technologies. The app aims to offer an adaptive and motivating running experience while ensuring user privacy through on-device processing.
Key Features:
• Personalized Coaching:
• Utilize real-time biometric data and personal insights to deliver AI-driven coaching tailored to the user’s mental and physical state.
• Analyze health metrics, activity data, mood check-ins, and more to provide context-based motivational feedback.
• Privacy First:
• All data processing occurs on-device using Apple’s frameworks like Core ML, ensuring no personal data leaves the device.
• Adaptive Motivation:
• Implement Natural Language Processing to analyze user inputs like journal entries or mood check-ins.
• Generate personalized coaching cues based on historical performance and mood trends.
• Performance Enhancement:
• Offer dynamic adjustments to pace, route, and strategy in real time to help improve running performance.
• Seamless integration with Apple Watch for real-time data collection and haptic feedback.
Technologies and Frameworks Involved:
• HealthKit: Access health metrics such as heart rate, distance run, VO₂ max, sleep patterns, etc.
• Core ML: On-device machine learning for real-time data analysis without latency.
• Natural Language Processing: Analyze personal inputs for better coaching personalization.
• Core Motion & Core Location: Track motion data and location services for runs.
• AVFoundation & Speech: Provide real-time voice feedback and coaching cues.
• SiriKit Integration: Allow users to initiate workouts and receive updates via Siri.
Target Audience:
• Runners of all levels seeking personalized coaching that adapts to their mental and physical states.
• Users who prioritize privacy and want AI-driven insights without their data leaving the device.
• Tech-savvy fitness enthusiasts who use iOS devices and Apple wearables.
Questions for the Community:
1. Feasibility: Is this idea technically achievable using current iOS frameworks and technologies?
2. Data Access: Are there limitations in accessing and processing the necessary data on-device, especially regarding privacy and permissions?
3. Potential Challenges: What hurdles might developers face in creating such an app, and how could they be addressed?
4. Advice: As someone without a technical background, what steps would you recommend I take to move this idea forward?
I truly appreciate any feedback or insights you can provide. I’m excited about the potential of this idea but also aware there may be complexities I’m not considering. Thank you for taking the time to read this!
Best regards,
Paul
I’ve developed an automation and shortcut using the iPhone Shortcuts app in IOS 18, something that hasn’t been done before. With support from Apple’s customer service, I was encouraged to bring this idea to life.
The automation’s purpose is to open a specified iOS app, move it to the background, and use a txt database in Folders to ensure uninterrupted data flow and continuous connectivity—especially useful for health apps where wearable devices need consistent, uninterrupted operation and monitoring (e.g., doctor tracking or wearable device connectivity). I would like to share the Automation and the Shortcut with the community.
Hi,
I am using HealthKit for the first time.
I am using HKStatisticsCollectionQuery.
I am running my code iOS 17 on a physical iPhone.
It takes several seconds to query data, for example 1 day worth of heart rate at 1 minute resolution. I changed the resolution to 1 hour, expecting it to be faster, but it's pretty much the same…
I have been following the official documentation and sample code.
I also compiled in Release, but that didn't really help for HKStatisticsCollectionQuery.
I quickly looked with Instruments, the app is spending a lot of time in decoding data with NSXPCDecoder.
Is there a way to speed data retrieval? Or this is "expected" latency?
Can’t start fitness video with my iPhone on my tv since new update 18.1. Air play is connecting I see the countdown then the dots rolling but nothing happens and I end up receiving a « can’t read video » message.
I’m using an iphone 16 pro max, an apple watch ultra (1st gen) and an apple tv HD (A1625 model).
I have almost the same issue with a more recent Apple TV, but on that one it’s just painfully long before the video starts but it does start eventually (just taking much longer than it used to). That some tv is an A2843 model (apple tv 4k 3rd gen).
Has anyone else had this issue?
I've realised with the sample code from the WWDC video below I'm getting the following error when trying to use the iPhone simulator and apple watch simulator paired.
Whenever i try to test out the sample project I'm getting the following error.
Failed to send data: Error Domain=com.apple.healthkit Code=300 "Remote device is unreachable" UserInfo={NSLocalizedDescription=Remote device is unreachable, NSUnderlyingError=0x600000c9c900 {Error Domain=RPErrorDomain Code=-6727 "kNotFoundErr ('rapport:rdid:PairedCompanion' not found)" UserInfo={cuErrorDesc=kNotFoundErr ('rapport:rdid:PairedCompanion' not found), cuErrorMsg='rapport:rdid:PairedCompanion' not found, NSLocalizedDescription=kNotFoundErr ('rapport:rdid:PairedCompanion' not found)}}}
Is it not possible to not test out the new WorkoutKit mirroring API's using the simulator?
Currently right now if you run the project you'll notice that you can start a workout session on the iPhone > Apple Watch but there is no way to control and mirror on both devices at the moment i.e You can't control the iPhone app on the Apple Watch and vice versa.
Also because of this the iPhone can't send data to the Apple Watch i.e. pause, end, water etc. I'm guessing this is meant to be possible since it seems a bit strange to only be able to test this out with actual devices.
WWDC Session
https://developer.apple.com/wwdc23/10023
Sample Code
https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/building_a_multidevice_workout_app
Apple is using the RPE scale for workout effort scores. This stands for the Rate of Perceived Exertion. They're specifically using the CR-10 scale, at least from what I can tell by saving values to HealthKit. They only accept value between 0 and 10.
Has anyone been able to find a scientific or academic paper on how they have chosen their different effort breakouts?
Right from the Fitness app on iPhone and Activity app on Apple Watch:
1-3 Easy
4-6 Moderate
7-8 Hard
9-10 All Out
There is zero documentation on these new types, which makes it difficult for workout recording apps to properly and appropriately save this new data type. Sure, we can use the Apple apps as a reference, but since there isn't a built-in Apple SwiftUI sheet to present this data, and no references to academia to point our users to, our solutions would just look the same.
FB15315876 - Documentation / HealthKit: Publish documentation about .workoutEffortScore and .estimatedWorkoutEffortScore
FB15316109 - Documentation / HealthKit: Add documentation to .estimatedWorkoutEffortScore and .workoutEffortScore that you can't save those samples via the save API and that they must be related and let that API save the sample
FB15316251 - Documentation / HealthKit: Add documentation for acceptible values of .estimatedWorkoutEffortScore and .workoutEffortScore - don't rely on a runtime error!
Apple missed making an enum for all third party developers this year.
There's no option to help me turn it on in my iPhone 16 Pro Max MYW43LL/A (iOS 18.1 developer beta) and Apple Watch Series 10 MWX13LW/A (watchOS 11 Developer Beta).
Hello everyone,
I'm developing an app for visionOS that utilizes HealthKit to query heart rate data. However, I'm encountering an issue where the app doesn't retrieve the latest heart rate values. Specifically, it fails to get live heart rate data even after the data has been saved to the Health app. The readings my app displays are outdated and do not match the current values shown in the Health app.
Here's what I've tried so far:
Fetching Heart Rate Samples: Used HKSampleQuery and HKAnchoredObjectQuery to fetch the most recent heart rate samples. Despite this, the data retrieved is still not up-to-date.
Checking Permissions: Ensured that all necessary HealthKit permissions are granted. The app has authorization to read heart rate data and write workout data.
My questions are:
Is there a known issue or limitation with HealthKit on visionOS that prevents apps from accessing the latest heart rate data?
Are there additional steps or configurations required to access live heart rate data in visionOS apps?
Has anyone successfully implemented live heart rate monitoring on visionOS, and if so, could you share how you achieved it?
Is there anywhere that describes in detail how third party workout apps can use the new effort score functionality? I can't see much in the documentation or any of the WWDC videos.
In particular it would be useful to know if an effort score is automatically calculated for workouts created with third party apps? It doesn't seem to happen but some people say it takes weeks / months before watchOS starts calculating it for third party apps.
If it doesn't happen automatically then how can the app set it? I tried the new relateWorkoutEffortSample API but that didn't work for me (see https://developer.apple.com/forums/thread/763539).
If I could get it working then how should I determine a default effort score based on the workout metrics? Is that something that the app should do? If so then it would be good to be consistent with watchOS so some idea of how that is calculating effort scores would be useful.
Sorry for all the questions, especially if there is an article in the documentation or a video that I have missed.
I am encountering issues on my device running iOS 18 that fetching heart rate samples associated to a given workout is very slow. Like 10+ seconds slow. This is unacceptable and unexpected.
In producing a video to attach to a feedback, I also observed that Apple Health app displays incorrect information if a workout effort score is associated to a workout.
In this image, you can see the Health app bug:
Total Resting Energy != Estimated Workout Effort Score
Here is the same workout after I delete the workout effort score using the Apple Health app:
Can anyone else see if attempting to view 'heart rate' data within the workout summary in Apple Health is unbearably slow if that workout also has an effort score associated?
My steps:
Record workout (Apple Activity app on watchOS)
Associate effort score
View the workout on Apple Health (iOS)
Attempt to view it's heart rate samples
Observe very slow loading times
Observe the incorrect cell label and value and disappearance of resting energy cell data
Remove/disassociate the effort score from the workout by tapping the workout effort row, and swipe to delete the value.
Navigate back, navigate back, and then go into the workout detail again
At this time the UI fixes itself, but the loading of heart rate data is still super slow
FB15269657 - HealthKit: Sample query to fetch heart rate samples associated to a workout is taking over 10 seconds - computing 'time in heart rate zone'
FB15278790 - Health: Workout summary 'Total Resting Energy' label has value of 'Estimated Workout Effort Score' for a value, pushed view shows empty
When a workout session is being recovered, if it is paused, the elapsed time will be incorrect. It will seem like that workout never was paused.
The recovery works fine if the workout was never paused.
Steps to reproduce:
Implement recoverActiveWorkoutSession
Start workout
Pause session and print the elapsed time
Stop simulator / cause crash
When recoverActiveWorkoutSession is called the elapsed time will not equal the elapsed time when the session was paused.
Here is my implementation. I haven't seen any examples online.
guard let recovered = try? await healthStore.recoverActiveWorkoutSession() else {return}
self.session = recovered
self.builder = recovered.associatedWorkoutBuilder()
self.session?.delegate = self
self.builder?.delegate = self
self.builder?.dataSource = HKLiveWorkoutDataSource(healthStore: healthStore, workoutConfiguration: recovered.workoutConfiguration)
self.sessionState = recovered.state
I'm using Healthkit with the following H/W specs:
Apple Watch, series 8, OS: 10.6.1 (21U580)
iPhone 11 Pro, OS: 17.6.1
Mac Studio M1
Xcode ver: 16.0 (16A242d)
I am trying to get Apple Watch to report heart rate, HRV, respiratory rate, and body temperature using Healthkit's HKLiveWorkoutBuilder implementing HKLiveWorkoutBuilderDelegate's workoutBuilder method. However, the only reported value that is found from the workoutBuilder method's collectedTypes (a Set of HKSampleType objects) is HKQuantityTypeIdentifierHeartRate. Nothing for HRV, respiratory rate, or body temperature. All entitlements are set up, the plist filled in, and capabilities in place. Not sure why only the heart rate is reported from the watch but nothing else.
I've scoured StackOverflow, Apple developer forums, even ChatGPT but none of the solutions work.
Any help most appreciate!
The model code is:
import Foundation
import HealthKit
class WatchModel: NSObject, HKLiveWorkoutBuilderDelegate, HKWorkoutSessionDelegate {
private let healthStore = HKHealthStore()
private var workoutSession: HKWorkoutSession!
private var workoutBuilder: HKLiveWorkoutBuilder!
override init() {
super.init()
requestAuthorization()
startWorkoutSession()
}
private func requestAuthorization() {
let heartRateType = HKQuantityType.quantityType(forIdentifier: .heartRate)!
let respiratoryRateType = HKQuantityType.quantityType(forIdentifier: .respiratoryRate)!
let HRVRateType = HKQuantityType.quantityType(forIdentifier: .heartRateVariabilitySDNN)!
let temperatureRateType = HKQuantityType.quantityType(forIdentifier: .bodyTemperature)!
let healthDataTypes: Set = [heartRateType, respiratoryRateType, HRVRateType, temperatureRateType]
healthStore.requestAuthorization(toShare: healthDataTypes, read: healthDataTypes) { (success, error) in
if !success {
print("Authorization failed")
}
}
}
func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) {
}
func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: any Error) {
}
func workoutBuilderDidCollectEvent(_ workoutBuilder: HKLiveWorkoutBuilder) {
}
func startWorkoutSession() {
let configuration = HKWorkoutConfiguration()
configuration.activityType = .other
configuration.locationType = .indoor
do {
workoutSession = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
workoutBuilder = workoutSession.associatedWorkoutBuilder()
workoutBuilder.delegate = self
workoutBuilder.dataSource = HKLiveWorkoutDataSource(healthStore: healthStore, workoutConfiguration: configuration)
let dataSource = HKLiveWorkoutDataSource(healthStore: healthStore, workoutConfiguration: configuration)
let respiratoryRate = HKQuantityType(.respiratoryRate)
dataSource.enableCollection(for: respiratoryRate, predicate: nil)
let bodyTemp = HKQuantityType(.bodyTemperature)
dataSource.enableCollection(for: bodyTemp, predicate: nil)
let hrv = HKQuantityType(.heartRateVariabilitySDNN)
dataSource.enableCollection(for: hrv, predicate: nil)
workoutSession.delegate = self
workoutSession.startActivity(with: Date())
workoutBuilder.beginCollection(withStart: Date(), completion: { (success, error) in
if let error = error {
print("Error starting collection: \(error.localizedDescription)")
}
})
} catch {
print("Failed to start workout session: \(error.localizedDescription)")
}
}
func workoutBuilder(_ workoutBuilder: HKLiveWorkoutBuilder, didCollectDataOf collectedTypes: Set<HKSampleType>) {
print("collected types: \(collectedTypes)")
for type in collectedTypes {
if let quantityType = type as? HKQuantityType {
if quantityType == HKQuantityType.quantityType(forIdentifier: .heartRate) {
if let heartRateQuantity = workoutBuilder.statistics(for: quantityType)?.mostRecentQuantity() {
let heartRateUnit = HKUnit(from: "count/min")
let heartRateValue = heartRateQuantity.doubleValue(for: heartRateUnit)
print("heart rate: \(heartRateValue)")
}
}
if quantityType == HKQuantityType.quantityType(forIdentifier: .heartRateVariabilitySDNN) {
if let hrvQuantity = workoutBuilder.statistics(for: quantityType)?.mostRecentQuantity() {
let hrvUnit = HKUnit.secondUnit(with: .milli)
let hrvValue = hrvQuantity.doubleValue(for: hrvUnit)
print("HRV: \(hrvValue)")
}
}
if quantityType == HKQuantityType.quantityType(forIdentifier: .bodyTemperature) {
if let bodyTempQuantity = workoutBuilder.statistics(for: quantityType)?.mostRecentQuantity() {
let tempUnit = HKUnit.degreeCelsius()
let tempValue = bodyTempQuantity.doubleValue(for: tempUnit)
print("body temp: \(tempValue)")
}
}
if quantityType == HKQuantityType.quantityType(forIdentifier: .respiratoryRate) {
if let respRateQuantity = workoutBuilder.statistics(for: quantityType)?.mostRecentQuantity() {
let respRateUnit = HKUnit(from: "count/min")
let respRateValue = respRateQuantity.doubleValue(for: respRateUnit)
print("breathing: \(respRateValue)")
}
}
}
}
}
}
My team and I are working on an app for a private emergency helpline.
Now as far as I understand the (sparse) API documentation for fall detection, given the appropriate entitlement, the following happens upon a detected fall:
The Standard UI will be opened with the options to a) call SOS b) acknowledge the fall but state that you're fine though, c) deny the fall, and (implicitly after 60 seconds on inactivity) call SOS because you didn't react.
All fall detection apps will then receive a bit of background time and get the func fallDetectionManager(CMFallDetectionManager, didDetect: CMFallDetectionEvent, completionHandler: () -> Void) called with the appropriate event value.
Now that's all good and it sounds like the custom fall detection is additive to the standard system.
But but why is there something like that in the entitlement request form sheet:
For any emergency calling features that you do not provide, explain any mitigations you use to make sure the user receives emergency services support that’s as close as possible to what they’d receive had they placed an emergency call natively.
This sounds like our app would rather be a drop-in to the standard SOS service – in contrast to being additive and also in contrast to what the API documentation infers.
Am I misunderstanding something?
I'm trying to hook into the new workoutEffort score supported in iOS 18, I am collecting this information from users when they submit their workout and trying to add a sample to the HKWorkout in the same manner as I've been adding other samples like bodyweight, calories burned, etc.
I'm receiving the error:
HKWorkout: Sample of type HKQuantityTypeIdentifierWorkoutEffortScore must be related to a workout
I tried adding the samples using HKWorkoutBuilder.add([samples]) as which has been working perfectly for calories burned & bodyweight, but I am receiving the above error for workoutEffortScore
As a second approach, I tried adding the sample after I called finishWorkout on the HKWorkoutBuilder and received back the HKWorkout object using HKHealthStore.add([samples], to: HKWorkout) and am still receiving the same error!
I don't know otherwise how to relate a sample to a workout, I thought those were the APIs to do so? I'm using Xcode 16.0 RC (16A242) and testing on an iOS 16 Pro simulator
I noticed last night that workouts I have been recording on my main carry device running 17.6.x have not been syncing to my beta devices running iOS 18 RC, iPadOS 18 RC and watchOS 11 RC.
All devices are using the same Apple Account and I have iCloud enabled for Health data. The iPad running the RC has the syncing enabled in Profile.
Is anyone else experiencing health data not propagating to the 18.x devices? Some of data exists on all devices but not all. For good measure I left the device unlocked on the health app last night for a long period of time to let it do its thing. This morning the data still hadn't propagated.
I disabled and reenabled the synchronization on my iPad having chosen to delete all samples when disabling it. Hopefully all of my data dating back to the first Apple Watch in 2014 restores.
FWIW my data set according to iCloud settings my health dataset is just shy of 650 MB.
FB15102443 - Health / HealthKit: Workouts, activity rings, sample data, and more not syncing via iCloud to 18 RC device
Hello HealthKit Experts & Enthusiasts!
I am building an app called one sec which forces people to take a deep breath before they can use social media apps (it’s using Shortcuts Automations for that).
One important feature of one sec is the Good Morning Countdown:
For a specified time after waking up (e.g. 30mins) selected apps are blocked completely. This helps to start the day screen-free.
They way it works is, the user grants access to read HKCategoryTypeIdentifier.sleepAnalysis data.
I have implemented a HKObserverQuery and enableBackgroundDelivery in order to be informed whenever new HKCategoryTypeIdentifier.sleepAnalysis becomes available.
I noticed that when I have my device connected to Xcode, this works as expected. However, when I quit the app and launch it from my Home Screen, my observer query is not informed about new sleep data (except when my app is running in foreground). Any ideas?
Furthermore, I have noticed that sometimes sleep data is provided delayed to HealthKit, many minutes (sometimes even longer) after waking up, no sleep samples are to be found in the Health app. Of course, for my app it is crucial to get accurate + timely so apps can be blocked accordingly.
Is this an issue that the Apple Watch first needs to send the samples to the phone?
Thanks a lot for your help!
Finally at last Apple Health supports saving .distancePaddleSports, .distanceCrossCountrySkiing, .distanceRowing, .distanceSkatingSports, and much more.
The backstory. In the land of 10,000 lakes, there hasn't been a way to save 'canoe' or 'kayak' distance and I've been asking for it for years. Thank you health team for adding it this year!
FB7807993 - Add HKQuantityTypeIdentifier.paddleDistance for canoeing, kayaking, etc type workouts (June 2020)
Prior we could just save the totalDistance to a workout, but since the HKWorkout initializers were deprecated we no longer have a supported way to save these distances in our workouts. The iOS 18 / watchOS 11 introduction addresses this. If you want to know more why you can't do this in earlier versions you can check these feedback titles:
FB10281482 - HealthKit: Deprecation of totalDistance on a workout session of paddleSports breaks apps that used that to save distance to the workout because there is no "paddleDistance" type available to save as sample data (June 2022)
FB12402974 - HealthKit: Deprecation of HKWorkout completely breaks support for third party fitness apps from saving non-standard workout distance (June 2023)
Great, so there is new support that solves all of these requests and issues for the new version of the OSes. However, the downside is now that there is not much for documentation. Unlike the .runningSpeed and .runningPower introduced in iOS 16 / watchOS 9, none of the new iOS 18 / watchOS 11 types have documentation, at all. To some degree this is understandable, but types from last year still remain undocumented too.
Without this information for the data types introduced in both iOS 17/18 and watchOS 10/11 it makes building and integrating with these new types difficult to say the least. We can't make assumptions about anything.
Can we get a documentation update for new (and existing) quantity types for when Apple Watch will automatically generate samples?
FB14236080 - Developer Documentation / HealthKit: Update documentation for HKLiveWorkoutDataSource typesToCollect for which sample types are automatically collected by watchOS 10 and 11 (July 2024)
FB14942555 - HealthKit / Documentation: App Update Release Issue - HKQuantityTypeIdentifiers are missing documentation describing when the system automatically adds data (today)
I know that the behavior has changed from release to release for some of these types, so documentation would be based on OS version. If you didn't catch it, watchOS 11 will now associate .cyclingSpeed for cycling workouts both indoor and outdoor.
FB12458548 - Fitness: Connected cycling speed sensor did not save samples to health via cycling workout (June 2023 - received reply that only saved for indoor cycling, but not documented otherwise)
FB14311218 - HealthKit: Expected outdoor cycling to include .cyclingSpeed quantity type as a default HKLiveWorkoutDataSource type to collect (July 2024)
To the other third party fitness apps out there, how are you managing the knowledge of which devices collect which data types on which versions of the OS?
Sure, we could look at the HKLiveWorkoutDatSource and inspect the typesToCollect property across a bunch of devices, but again that is trial by error not 'as documented'. Is the behavior of simulators guaranteed to match the behavior of real devices? Maybe, but also maybe not.
Fingers crossed for a nice documentation update to spell out all of the behavioral details.
Apple folks / DTS, many of the above feedbacks are addressed and I plan to update or close them after the releases this fall. Some are still outstanding.
P.S. I hope that .paddleSports gets deprecated and split into individual activity types like skiing did years ago. Their MET scores are different according to the research on the physical activity compendium site.
FB7807902 - Split HKWorkoutActivityType.paddleSports into their own activity types (June 2020)
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
}
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.