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

Enabling Healthkit on Xcode 14 - Doesn't Work
Hello fellow developers, I'm using Xcode 14, MacOS 13.2, and trying to make an iPhone and Apple Watch companion app using HealthKit. I'm getting the following error: Code=4 "Missing com.apple.developer.healthkit entitlement." UserInfo={NSLocalizedDescription=Missing com.apple.developer.healthkit entitlement.} From this line of code: private var healthStore = HKHealthStore() Since Xcode there is no Info.plist file and I've tried adding it but the build fails if I add a properties file that is called Info.plist. I've seen recent documentation that states to use project -> Info -> Custom iOS Target Properties and values such as: "Privacy - Health Update Usage Description" and add a description greater than 12 characters. However, this property and other properties that I add to this section section disappear when I navigate away from that tab. This is weird because if I try to re-enter that value, I am presented with a dialog that states, "Replace Existing Pair". Again, I can add it and then navigate away and it disappears. Regardless, I can't find any documentation in the Apple developer forums or any other part of the Internet. Is this a bug?
1
0
833
Feb ’23
HealthKit sleep analysis
Until the last Apple Watch update I was retrieving sleep data from HealthKit using the .asleep identifier and reliable got sleep and the date the sleep was credited to in Apple Health. Since the update there appears to be no reliable way to make sure that the sleep calculated from the various sleep states get credited to the same day Apple Health credits the sleep to. We have no interest in analyzing sleep states, all we want is total sleep for a given day and that the date for the sleep is the same as Apple Health displays. How can this be reliably achieved?
1
0
1.8k
Feb ’23
Decrypting HRV data from healthdb_secure.sqlite
Hello, i am currently working on an university project about the forensic usage of fitness tracker data. To this point I already extracted the healthdb_secure.sqlite database from an encrypted iPhone Backup. I was able to get all data visualized in the HealthApp. At least I got one problem. The heart rate variability. I can extract the summarized value shown in the health app, but I got big issues to get the beat to beat measurement. I am stuck at this point: The hrv entries can be found in the samples table under the data_type = 139. With a left outer join with associations on samples.data_id = associations.child_id you get the corresponding parent_id. Only for each parent_id there is an entry in the binary_samples table with an associated byte array. I am currently trying to decode this byte array, but it’s very hard to get data from this. so my question is, if anybody knows how to decode this byte array or if somebody know how to get the beat to beat measurement for each heart rate variability entry. best regards
1
0
956
Feb ’23
HealthKit HKWorkout totalEnergyBurned
I have an app that adds cycling workouts to HealthKit. Here is the snippet of code that does it. let workout = HKWorkout( activityType: HKWorkoutActivityType.cycling, start: startTime, end: endTime, duration: 0, // compute from start and end data totalEnergyBurned: HKQuantity( unit: .largeCalorie(), doubleValue: Double(calories) ), totalDistance: HKQuantity(unit: .mile(), doubleValue: distance), metadata: nil ) try await store.save(workout) This successfully adds a workout and the number of calories is recorded in the Health app. However, the iOS Fitness app and the watchOS Activity app do not recognize the calories so the MOVE ring is not affected. What else do I need to do to let those apps know that my workout burned calories?
2
0
1k
Feb ’23
cycling workouts
I wrote an app that successfully adds a cycling workout to HealthKit. I can see in the Health app that there are new entries under "Workouts", "Active Energy", and "Exercise Minutes" all from me just adding an HKWorkout and a HKQuantitySample. However, there is no new entry for "Cycling Distance". I assumed that since the workout I added includes the fact that the activityType is HKWorkoutActivityType.cycling and I provided the distance, that it would also add an entry for "Cycling Distance". Is there something extra I need to do to get that?
2
0
1.2k
Feb ’23
Can a watchOS app with 'workout processing' background mode be sent to background?
Hi A watchOS app that has the property 'Required Background mode (Watch)' set to 'Workout processing' always stay in the foreground. This is what I want and correct. But, the app stays in the foreground regardless if there is an active HKWorkoutSession or not. During an active HKWorkoutSession this is perfectly fine but before a workout has started of after it has ended the app should not stay in the foreground. The only possibility a user has is to use the app-switcher and kill the app, otherwise it will always come to the foreground. Is there a possibility to set the 'required background mode' at runtime? Or any other possibility to control if the app should stay in foreground or not? many thanks for any help Thomas
0
0
919
Mar ’23
Accessing the APi
This is from the code in the video on Exploring Verifiable Health records. @ the 10:28 mark I get an error saying cannot find predicaetForVerifiableClincalRecords in Scope. import HealthKit import Foundation let healthStore = HKHealthStore() let recordTypes = ["https://smarthealth.cards#immunization"] let endDate = Date() let startDate = Calendar.current.date(byAdding: .day, value: -7, to: endDate) let dateInterval = DateInterval(start: startDate ?? .now, end: endDate) let predicate = predicateForVerifiableClinicalRecords(withRelevantDateWithin: dateInterval) <- error here
1
0
578
Mar ’23
ECG Anomaly Dataset
I am a undergraduate research student at a university lab. I am looking to find raw data for the anomaly detection of ECG measured by the apple watch. I understand that Healthkit provides a visual graph of the ECG data. However, I am in need of the numerical data for research purposes. Is there a way for me to get to this dataset?
2
0
2.1k
Mar ’23
healthkit restingHeartRate simulator
I try to get data of the restingHeartRate via HKStatisticsCollectionQuery. The simulator doesnt seems to have any records. I can retrieve active heart rate data, and I collected those via a HKWorkoutSession. I set the authorization: ` let readDataTypes: Set = [ HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.restingHeartRate)!, HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.biologicalSex)!, HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.dateOfBirth)!, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!, ]` The code will retrieve data if I change .restingHeartRate to .heartRate let calendar = Calendar.current let beatsPerMinuteUnit = HKUnit.count().unitDivided(by: HKUnit.minute()) let restingHeartRateType = HKQuantityType.quantityType(forIdentifier: .restingHeartRate)! let endDate = Date() let startDate = calendar.date(byAdding: .day, value: -14, to: endDate)! let restingPredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: []) let anchorDate = calendar.date(bySettingHour: 0, minute: 0, second: 0, of: Date())! var interval = DateComponents() interval.day = 1 let restingHRquery = HKStatisticsCollectionQuery(quantityType: restingHeartRateType, quantitySamplePredicate: restingPredicate, options: .discreteAverage, anchorDate: anchorDate, intervalComponents: interval) restingHRquery.initialResultsHandler = { restingQuery, statisticsCollection, error in guard let statsCollection = statisticsCollection else { return} print ("statsCollection init \(statsCollection.statistics().count)") } restingHRquery.statisticsUpdateHandler = { restingQuery, statistics, statisticsCollection, error in guard let statsCollection = statisticsCollection else { return } print ("statsCollection update\(statsCollection.statistics().count)") Any advice on how to retrieve some test data?
2
0
448
May ’23
Observe HealthKit data changes with locked iPhone by Face ID
Hi, I have tried to observe HealthKit data (workouts) with background delivery, but I am faced with a problem - updates don't come when iPhone is locked by Face ID. Everything works fine with an unlocked device. I didn't find any references in the documentations. Is this the expected behavior? Code: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { HealthManager.shared.startObservingWorkouts { /* Don't receive updates */ } return true } } class HealthManager { static let shared: HealthManager = .init() private let hkStore = HKHealthStore() init() { } func startObservingWorkouts(handleUpdates: @escaping ([HKWorkout]) -> Void) { hkStore.getRequestStatusForAuthorization( toShare: [], read: [.workoutType()]) { [weak self] status, _ in guard status == .unnecessary else { return } let prediction = HKQuery.predicateForSamples( withStart: Date().startOfDay, end: Date().endOfDay, options: [.strictStartDate, .strictEndDate] ) let query = HKObserverQuery( sampleType: .workoutType(), predicate: prediction, updateHandler: { [weak self] _, completionHandler, _ in self?.getWorkouts { handleUpdates($0 ?? []) completionHandler() } } ) self?.hkStore.execute(query) self?.hkStore.enableBackgroundDelivery( for: .workoutType(), frequency: .immediate ) { _, error in print(error) } } } private func getWorkouts(handleResult: @escaping ([HKWorkout]?) -> Void) { let prediction = HKQuery.predicateForSamples( withStart: Date().startOfDay, end: Date().endOfDay, options: [.strictStartDate, .strictEndDate] ) let query = HKSampleQuery( sampleType: .workoutType(), predicate: prediction, limit: HKObjectQueryNoLimit, sortDescriptors: nil ) { query, samples, error in if error != nil { return } guard let samples = samples else { fatalError("*** Invalid State: This can only fail if there was an error. ***") } guard let workouts = samples as? [HKWorkout] else { return } handleResult(workouts) } hkStore.execute(query) } } @main struct HealthKitTestApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } }
1
0
717
May ’23
Crash on fetching health kit data
I am receiving the following crash when trying to query data from health kit. It seems to be complaining about end date being before start date however with the values I am passing in that is not possible. Also I tried to purposefully pass in end dates before start date and I still was not able to reproduce this crash. I have attached my code snippet and the crash logs here. Please Help :( self.statisticfetcher( type: HKObjectType.quantityType(forIdentifier: .bodyMass), options: .discreteAverage, metricType: .bodyWeight, statsHandler: { stats in if let quantity = stats.averageQuantity() { ... } return nil }) private func statisticfetcher( type: HKQuantityType?, options: HKStatisticsOptions, metricType: HealthMetricType, statsHandler: @escaping (HKStatistics) -> BASchema.HealthDataEntryInput?, resultHandler: ((HKStatisticsCollection?, Date, Date, Error?) -> Void)? = nil) { let res = getStartEndDate() let endDate = res.endDate let startDate = res.startDate guard let type = type else { return } let query = HKStatisticsCollectionQuery(quantityType: type, quantitySamplePredicate: nil, options: options, anchorDate: startDate, intervalComponents: DateComponents(day: 1)) let defaultResultHandler: (HKStatisticsCollection?, Date, Date, Error?) -> Void = { statCollection, startDate, endDate, error in if let error = error { return } guard let statCollection = statCollection else { return } statCollection.enumerateStatistics(from: startDate, to: endDate) { stats, _ in ... } } let resultHandler = resultHandler ?? defaultResultHandler query.initialResultsHandler = { _, statCollection, error in resultHandler(statCollection, startDate, endDate, error) } query.statisticsUpdateHandler = { _, _, statCollection, error in resultHandler(statCollection, startDate, endDate, error) } self.store.execute(query) self.subscribeToBackgroundDelivery(type: type) } private func subscribeToBackgroundDelivery(type: HKObjectType) { store.enableBackgroundDelivery(for: type, frequency: .immediate) { success, error in if(error != nil && !success) { print("Background Delivery for \(type) Failed!") } } }``` Fatal Exception: NSInternalInconsistencyException 0 CoreFoundation 0x9cb4 __exceptionPreprocess 1 libobjc.A.dylib 0x183d0 objc_exception_throw 2 Foundation 0x4e156c _userInfoForFileAndLine 3 HealthKit 0xe0d2c -[HKDateInterval initWithStartDate:endDate:] 4 HealthKit 0xc7a5c -[NSDateComponents(HealthKit) hk_dateIntervalForDate:anchorDate:outIndex:] 5 HealthKit 0x1a0f98 -[HKStatisticsCollection _statisticsDateIntervalAndIndex:forDate:] 6 HealthKit 0x1a0420 -[HKStatisticsCollection _insertStatistics:] 7 HealthKit 0x1a059c -[HKStatisticsCollection _resetStatistics:] 8 HealthKit 0x19efc8 -[HKStatisticsCollectionQuery _queue_deliverResetStatisticsObjects:forQuery:] 9 HealthKit 0x19e8bc __98-[HKStatisticsCollectionQuery client_deliverStatisticsBatch:resetStatistics:isFinal:anchor:query:]_block_invoke 10 libdispatch.dylib 0x2320 _dispatch_call_block_and_release 11 libdispatch.dylib 0x3eac _dispatch_client_callout 12 libdispatch.dylib 0xb534 _dispatch_lane_serial_drain 13 libdispatch.dylib 0xc0d8 _dispatch_lane_invoke 14 libdispatch.dylib 0x16cdc _dispatch_workloop_worker_thread 15 libsystem_pthread.dylib 0xddc _pthread_wqthread 16 libsystem_pthread.dylib 0xb7c start_wqthread
4
0
1.5k
Sep ’23
Can I issue a single query HealthStore to get back multiple series
I am writing an app to retrieve the dive info from HealthStore (specifically HKQuantityTypeIdentifier.underwaterDepth and HKQuantityTypeIdentifier.waterTemperature. To get the data, I am using HKQuantitySeriesSampleQuery to get the discrete dive events or values so that I can export them to dive logs (e.g., Subsurface) or to graph the depth profile and temperature. I am able to fire the HKQuantitySeriesSampleQuery to get the depth and then another query to get the temperature. However, is there a way I can fire one query to get both depth and temperature. I would like to not join the two results if possible. Thanks in advance
0
0
432
May ’23
Enabling Healthkit on Xcode 14 - Doesn't Work
Hello fellow developers, I'm using Xcode 14, MacOS 13.2, and trying to make an iPhone and Apple Watch companion app using HealthKit. I'm getting the following error: Code=4 "Missing com.apple.developer.healthkit entitlement." UserInfo={NSLocalizedDescription=Missing com.apple.developer.healthkit entitlement.} From this line of code: private var healthStore = HKHealthStore() Since Xcode there is no Info.plist file and I've tried adding it but the build fails if I add a properties file that is called Info.plist. I've seen recent documentation that states to use project -> Info -> Custom iOS Target Properties and values such as: "Privacy - Health Update Usage Description" and add a description greater than 12 characters. However, this property and other properties that I add to this section section disappear when I navigate away from that tab. This is weird because if I try to re-enter that value, I am presented with a dialog that states, "Replace Existing Pair". Again, I can add it and then navigate away and it disappears. Regardless, I can't find any documentation in the Apple developer forums or any other part of the Internet. Is this a bug?
Replies
1
Boosts
0
Views
833
Activity
Feb ’23
HealthKit sleep analysis
Until the last Apple Watch update I was retrieving sleep data from HealthKit using the .asleep identifier and reliable got sleep and the date the sleep was credited to in Apple Health. Since the update there appears to be no reliable way to make sure that the sleep calculated from the various sleep states get credited to the same day Apple Health credits the sleep to. We have no interest in analyzing sleep states, all we want is total sleep for a given day and that the date for the sleep is the same as Apple Health displays. How can this be reliably achieved?
Replies
1
Boosts
0
Views
1.8k
Activity
Feb ’23
Medication Tracking in Heathkit?
Does anyone know if the API for medication tracking in Apple Health is available / when it would be available by?
Replies
0
Boosts
5
Views
565
Activity
Feb ’23
Retrieve sleep schedule bedtime and wake up times
Is it possible to retrieve the sleep schedule wakeup and bedtime times using HealthKit? I can retrieve sleep analysis values, but I don't want the detailed data just the wake up and bedtime times the user has possibly specified in the health app, I can't see any way to retrieve those values. Thanks.
Replies
1
Boosts
1
Views
1.1k
Activity
Feb ’23
Apple HealthKit and store data in variables
I trying to save the height from apple HealthKit in variables but it is only 0.0 Moreover I get the height in the result handler but I can't save it to the var. Do you have any ideas? greeting Fabian
Replies
1
Boosts
0
Views
728
Activity
Feb ’23
Decrypting HRV data from healthdb_secure.sqlite
Hello, i am currently working on an university project about the forensic usage of fitness tracker data. To this point I already extracted the healthdb_secure.sqlite database from an encrypted iPhone Backup. I was able to get all data visualized in the HealthApp. At least I got one problem. The heart rate variability. I can extract the summarized value shown in the health app, but I got big issues to get the beat to beat measurement. I am stuck at this point: The hrv entries can be found in the samples table under the data_type = 139. With a left outer join with associations on samples.data_id = associations.child_id you get the corresponding parent_id. Only for each parent_id there is an entry in the binary_samples table with an associated byte array. I am currently trying to decode this byte array, but it’s very hard to get data from this. so my question is, if anybody knows how to decode this byte array or if somebody know how to get the beat to beat measurement for each heart rate variability entry. best regards
Replies
1
Boosts
0
Views
956
Activity
Feb ’23
Clinical Records Update to HealthKit
Is it possible to update clinical records, like allergy, vital, medication to HealthKit app. I'm able to read, now I looking to update
Replies
1
Boosts
0
Views
560
Activity
Feb ’23
HealthKit HKWorkout totalEnergyBurned
I have an app that adds cycling workouts to HealthKit. Here is the snippet of code that does it. let workout = HKWorkout( activityType: HKWorkoutActivityType.cycling, start: startTime, end: endTime, duration: 0, // compute from start and end data totalEnergyBurned: HKQuantity( unit: .largeCalorie(), doubleValue: Double(calories) ), totalDistance: HKQuantity(unit: .mile(), doubleValue: distance), metadata: nil ) try await store.save(workout) This successfully adds a workout and the number of calories is recorded in the Health app. However, the iOS Fitness app and the watchOS Activity app do not recognize the calories so the MOVE ring is not affected. What else do I need to do to let those apps know that my workout burned calories?
Replies
2
Boosts
0
Views
1k
Activity
Feb ’23
cycling workouts
I wrote an app that successfully adds a cycling workout to HealthKit. I can see in the Health app that there are new entries under "Workouts", "Active Energy", and "Exercise Minutes" all from me just adding an HKWorkout and a HKQuantitySample. However, there is no new entry for "Cycling Distance". I assumed that since the workout I added includes the fact that the activityType is HKWorkoutActivityType.cycling and I provided the distance, that it would also add an entry for "Cycling Distance". Is there something extra I need to do to get that?
Replies
2
Boosts
0
Views
1.2k
Activity
Feb ’23
Can a watchOS app with 'workout processing' background mode be sent to background?
Hi A watchOS app that has the property 'Required Background mode (Watch)' set to 'Workout processing' always stay in the foreground. This is what I want and correct. But, the app stays in the foreground regardless if there is an active HKWorkoutSession or not. During an active HKWorkoutSession this is perfectly fine but before a workout has started of after it has ended the app should not stay in the foreground. The only possibility a user has is to use the app-switcher and kill the app, otherwise it will always come to the foreground. Is there a possibility to set the 'required background mode' at runtime? Or any other possibility to control if the app should stay in foreground or not? many thanks for any help Thomas
Replies
0
Boosts
0
Views
919
Activity
Mar ’23
Accessing the APi
This is from the code in the video on Exploring Verifiable Health records. @ the 10:28 mark I get an error saying cannot find predicaetForVerifiableClincalRecords in Scope. import HealthKit import Foundation let healthStore = HKHealthStore() let recordTypes = ["https://smarthealth.cards#immunization"] let endDate = Date() let startDate = Calendar.current.date(byAdding: .day, value: -7, to: endDate) let dateInterval = DateInterval(start: startDate ?? .now, end: endDate) let predicate = predicateForVerifiableClinicalRecords(withRelevantDateWithin: dateInterval) <- error here
Replies
1
Boosts
0
Views
578
Activity
Mar ’23
ECG Anomaly Dataset
I am a undergraduate research student at a university lab. I am looking to find raw data for the anomaly detection of ECG measured by the apple watch. I understand that Healthkit provides a visual graph of the ECG data. However, I am in need of the numerical data for research purposes. Is there a way for me to get to this dataset?
Replies
2
Boosts
0
Views
2.1k
Activity
Mar ’23
Develop and integrate health testing APP
I want to develop an APP for testing vital signs. It can test heart rate, temperature, oxygen, and more at the same time. Does Apple provide any SDKs or APIs for things like heart rate and oxygen outside of Workout? Ask another way, that is, can I write the blood oxygen, temperature, etc. test function on my APP?
Replies
0
Boosts
0
Views
473
Activity
Apr ’23
healthkit restingHeartRate simulator
I try to get data of the restingHeartRate via HKStatisticsCollectionQuery. The simulator doesnt seems to have any records. I can retrieve active heart rate data, and I collected those via a HKWorkoutSession. I set the authorization: ` let readDataTypes: Set = [ HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.restingHeartRate)!, HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.biologicalSex)!, HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.dateOfBirth)!, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!, ]` The code will retrieve data if I change .restingHeartRate to .heartRate let calendar = Calendar.current let beatsPerMinuteUnit = HKUnit.count().unitDivided(by: HKUnit.minute()) let restingHeartRateType = HKQuantityType.quantityType(forIdentifier: .restingHeartRate)! let endDate = Date() let startDate = calendar.date(byAdding: .day, value: -14, to: endDate)! let restingPredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: []) let anchorDate = calendar.date(bySettingHour: 0, minute: 0, second: 0, of: Date())! var interval = DateComponents() interval.day = 1 let restingHRquery = HKStatisticsCollectionQuery(quantityType: restingHeartRateType, quantitySamplePredicate: restingPredicate, options: .discreteAverage, anchorDate: anchorDate, intervalComponents: interval) restingHRquery.initialResultsHandler = { restingQuery, statisticsCollection, error in guard let statsCollection = statisticsCollection else { return} print ("statsCollection init \(statsCollection.statistics().count)") } restingHRquery.statisticsUpdateHandler = { restingQuery, statistics, statisticsCollection, error in guard let statsCollection = statisticsCollection else { return } print ("statsCollection update\(statsCollection.statistics().count)") Any advice on how to retrieve some test data?
Replies
2
Boosts
0
Views
448
Activity
May ’23
Unable to reset fitness data on watch
Have tried several times to reset fitness data. iPhone 12 i os = 16.5 watch, 9.5 series 4
Replies
3
Boosts
0
Views
858
Activity
May ’23
splitTotalEnergy deprecated, is there any replacement?
I would like to use this https://developer.apple.com/documentation/healthkit/hkhealthstore/1614170-splittotalenergy but I saw that it's deprecated. Is there any replacement? Thanks!
Replies
0
Boosts
1
Views
899
Activity
May ’23
HKSamples matching metadata ?
Some HKDiscreteQuantitySample types have metadata. Is it possible to write a HKSampleQuery that would return samples that match a specific metadata param? Use case: getting heartRate samples that match a specific HKHeartRateMotionContex case (or its raw value).
Replies
0
Boosts
0
Views
350
Activity
May ’23
Observe HealthKit data changes with locked iPhone by Face ID
Hi, I have tried to observe HealthKit data (workouts) with background delivery, but I am faced with a problem - updates don't come when iPhone is locked by Face ID. Everything works fine with an unlocked device. I didn't find any references in the documentations. Is this the expected behavior? Code: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { HealthManager.shared.startObservingWorkouts { /* Don't receive updates */ } return true } } class HealthManager { static let shared: HealthManager = .init() private let hkStore = HKHealthStore() init() { } func startObservingWorkouts(handleUpdates: @escaping ([HKWorkout]) -> Void) { hkStore.getRequestStatusForAuthorization( toShare: [], read: [.workoutType()]) { [weak self] status, _ in guard status == .unnecessary else { return } let prediction = HKQuery.predicateForSamples( withStart: Date().startOfDay, end: Date().endOfDay, options: [.strictStartDate, .strictEndDate] ) let query = HKObserverQuery( sampleType: .workoutType(), predicate: prediction, updateHandler: { [weak self] _, completionHandler, _ in self?.getWorkouts { handleUpdates($0 ?? []) completionHandler() } } ) self?.hkStore.execute(query) self?.hkStore.enableBackgroundDelivery( for: .workoutType(), frequency: .immediate ) { _, error in print(error) } } } private func getWorkouts(handleResult: @escaping ([HKWorkout]?) -> Void) { let prediction = HKQuery.predicateForSamples( withStart: Date().startOfDay, end: Date().endOfDay, options: [.strictStartDate, .strictEndDate] ) let query = HKSampleQuery( sampleType: .workoutType(), predicate: prediction, limit: HKObjectQueryNoLimit, sortDescriptors: nil ) { query, samples, error in if error != nil { return } guard let samples = samples else { fatalError("*** Invalid State: This can only fail if there was an error. ***") } guard let workouts = samples as? [HKWorkout] else { return } handleResult(workouts) } hkStore.execute(query) } } @main struct HealthKitTestApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } }
Replies
1
Boosts
0
Views
717
Activity
May ’23
Crash on fetching health kit data
I am receiving the following crash when trying to query data from health kit. It seems to be complaining about end date being before start date however with the values I am passing in that is not possible. Also I tried to purposefully pass in end dates before start date and I still was not able to reproduce this crash. I have attached my code snippet and the crash logs here. Please Help :( self.statisticfetcher( type: HKObjectType.quantityType(forIdentifier: .bodyMass), options: .discreteAverage, metricType: .bodyWeight, statsHandler: { stats in if let quantity = stats.averageQuantity() { ... } return nil }) private func statisticfetcher( type: HKQuantityType?, options: HKStatisticsOptions, metricType: HealthMetricType, statsHandler: @escaping (HKStatistics) -> BASchema.HealthDataEntryInput?, resultHandler: ((HKStatisticsCollection?, Date, Date, Error?) -> Void)? = nil) { let res = getStartEndDate() let endDate = res.endDate let startDate = res.startDate guard let type = type else { return } let query = HKStatisticsCollectionQuery(quantityType: type, quantitySamplePredicate: nil, options: options, anchorDate: startDate, intervalComponents: DateComponents(day: 1)) let defaultResultHandler: (HKStatisticsCollection?, Date, Date, Error?) -> Void = { statCollection, startDate, endDate, error in if let error = error { return } guard let statCollection = statCollection else { return } statCollection.enumerateStatistics(from: startDate, to: endDate) { stats, _ in ... } } let resultHandler = resultHandler ?? defaultResultHandler query.initialResultsHandler = { _, statCollection, error in resultHandler(statCollection, startDate, endDate, error) } query.statisticsUpdateHandler = { _, _, statCollection, error in resultHandler(statCollection, startDate, endDate, error) } self.store.execute(query) self.subscribeToBackgroundDelivery(type: type) } private func subscribeToBackgroundDelivery(type: HKObjectType) { store.enableBackgroundDelivery(for: type, frequency: .immediate) { success, error in if(error != nil && !success) { print("Background Delivery for \(type) Failed!") } } }``` Fatal Exception: NSInternalInconsistencyException 0 CoreFoundation 0x9cb4 __exceptionPreprocess 1 libobjc.A.dylib 0x183d0 objc_exception_throw 2 Foundation 0x4e156c _userInfoForFileAndLine 3 HealthKit 0xe0d2c -[HKDateInterval initWithStartDate:endDate:] 4 HealthKit 0xc7a5c -[NSDateComponents(HealthKit) hk_dateIntervalForDate:anchorDate:outIndex:] 5 HealthKit 0x1a0f98 -[HKStatisticsCollection _statisticsDateIntervalAndIndex:forDate:] 6 HealthKit 0x1a0420 -[HKStatisticsCollection _insertStatistics:] 7 HealthKit 0x1a059c -[HKStatisticsCollection _resetStatistics:] 8 HealthKit 0x19efc8 -[HKStatisticsCollectionQuery _queue_deliverResetStatisticsObjects:forQuery:] 9 HealthKit 0x19e8bc __98-[HKStatisticsCollectionQuery client_deliverStatisticsBatch:resetStatistics:isFinal:anchor:query:]_block_invoke 10 libdispatch.dylib 0x2320 _dispatch_call_block_and_release 11 libdispatch.dylib 0x3eac _dispatch_client_callout 12 libdispatch.dylib 0xb534 _dispatch_lane_serial_drain 13 libdispatch.dylib 0xc0d8 _dispatch_lane_invoke 14 libdispatch.dylib 0x16cdc _dispatch_workloop_worker_thread 15 libsystem_pthread.dylib 0xddc _pthread_wqthread 16 libsystem_pthread.dylib 0xb7c start_wqthread
Replies
4
Boosts
0
Views
1.5k
Activity
Sep ’23
Can I issue a single query HealthStore to get back multiple series
I am writing an app to retrieve the dive info from HealthStore (specifically HKQuantityTypeIdentifier.underwaterDepth and HKQuantityTypeIdentifier.waterTemperature. To get the data, I am using HKQuantitySeriesSampleQuery to get the discrete dive events or values so that I can export them to dive logs (e.g., Subsurface) or to graph the depth profile and temperature. I am able to fire the HKQuantitySeriesSampleQuery to get the depth and then another query to get the temperature. However, is there a way I can fire one query to get both depth and temperature. I would like to not join the two results if possible. Thanks in advance
Replies
0
Boosts
0
Views
432
Activity
May ’23