Hello,
I am writing as I am seeing a very strange behavior when attempting to run an HKStatisticsCollectionQuery over multiple app starts.
Steps:
Initially load and launch my app into an iOS simulator (running iOS 17.2) via Xcode (version 15.3).
Execute code path which invokes the following method below.
Authorize necessary Read permission for the HKQuantityTypeIdentifierStepCount type.
Observed that a non-nil HKStatisticsCollection is returned in the initialResultsHandler, with corresponding expected datapoints. These datapoints are in no way stored or retained on the device at all.
Stop the app via Xcode.
Relaunch the app via Xcode.
Execute the same code path as in step 2.
Observed (via breakpoints) that even though the query is executed by the HKHealthStore, the initialResultsHandler is never called and no HKStatisticsCollection is ever returned.
Input parameters are the same in both instances of the call, and can confirm there is data in the devices HealthKit datastore.
I would expect, reading Apple's documentation, that both queries should execute and return the exact same datapoints in an HKStatisticsCollection, but please feel free to correct me if I am misunderstanding something, or if my code is incorrect in some way.
func fetchStatisticsCollection(with quantityType: HKQuantityType,
predicate: NSPredicate? = nil,
options: HKStatisticsOptions,
anchorDate: Date? = nil,
interval: DateComponents? = nil,
initialResultsCompletion: @escaping (Result<HKStatisticsCollection, Error>) -> Void,
updateHandler: (Result<HKStatisticsCollection, Error>) -> Void?) {
var statisticsQueryAnchorDate: Date = Date()
if let anchor = anchorDate {
statisticsQueryAnchorDate = anchor
} else if let yesterdayAnchor = createStaticsQueryAnchorDateYesterday(){
statisticsQueryAnchorDate = yesterdayAnchor
}
let dateInterval = interval ?? DateComponents(day: 1)
// Create the query
let query = HKStatisticsCollectionQuery(quantityType: quantityType,
quantitySamplePredicate: predicate,
options: options,
anchorDate: statisticsQueryAnchorDate,
intervalComponents: dateInterval)
// Set the results handler
query.initialResultsHandler = { query, results, error in
if let error = error as? HKError{
// Return wrapped HKError
initialResultsCompletion(.failure(HealthKitManagerError.hkError(error: error)))
return
}
guard let statsCollection = results else {
// Return custom Empty Results error.
initialResultsCompletion(.failure(HealthKitManagerError.emptyResults))
return
}
initialResultsCompletion(.success(statsCollection))
}
if let updateHandler = updateHandler {
query.statisticsUpdateHandler = { query, statistics, statisticsCollection, error in
if let error = error as? HKError{
// Return custom wrapped HKError.
updateHandler(.failure(HealthKitManagerError.hkError(error: error)))
return
}
guard let statsCollection = statisticsCollection else {
// Return custom Empty Results error.
updateHandler(.failure(HealthKitManagerError.emptyResults))
return
}
updateHandler(.success(statsCollection))
}
}
if activeTypeQueries[quantityType.identifier] == nil {
healthStore.execute(query)
activeTypeQueries[quantityType.identifier] = query
healthStore.enableBackgroundDelivery(for: quantityType, frequency: .immediate) { (success, error) in
if let error = error {
return
}
if success {
print("background enabled")
}
}
} else {
print("NOT executing query, we already have one query running for this type")
}
}
Thank you
Health & Fitness
RSS for tagExplore the technical aspects of health and fitness features, including sensor data acquisition, health data processing, and integration with the HealthKit framework.
Post
Replies
Boosts
Views
Activity
Hi All,
I have a strange issue. I am using enableBackgroundDelivery for updating user step count in background mode using health kit. It works fine when I execute the app by pressing 'Run' in xcode. But the code is not triggering when I am directly launching it on my device. I have tried many different things but cannot figure out the issue from 2 days π. I would really appreciate any suggestions.
Thanks
Hello, our app has been rejected in the review of version update, we need to provide relevant medical certificates. And our classification is Health and Fitness.However, our device is not a medical device and does not have a medical hardware regulatory license. How can I pass the audit?
βHello,
The issues we previously identified still need your attention.
If you have any questions, we are here to help. Reply to this message in App Store Connect and let us know.
Review Environment
Submission ID: e5e36844-23e5-41fc-a956-eb46746728c1
Review date: April 16, 2024
Version reviewed: 1.0.1
Guideline 1.4.1 - Safety - Physical Harm
The app connects to external medical hardware to provide medical services. However, to be compliant with guideline 1.4.1, you must:
Provide documentation from the appropriate regulatory organization demonstrating regulatory clearance for the medical hardware used by the app.
Provide documentation of a report or peer-reviewed study that demonstrates the app's use of medical hardware works as described.
Restrict distribution of the app to regions where you have obtained regulatory clearance for the medical hardware used by the app. Otherwise, you must provide a jurisdiction statement in the app description declaring where the medical hardware has regulatory clearance to be used.
Update the app's description to include a disclaimer reminding users to seek a doctorβs advice in addition to using this app and before making any medical decisions.
Next Steps
To resolve this issue, provide the documentation requested above, restrict your salable storefronts in App Store Connect or include a jurisdiction statement in the app description, and update your app's description in App Store Connect to include the required medical disclaimer.
Resources
Learn more about requirements for medical apps in guideline 1.4.1.
Support
Reply to this message in your preferred language if you need assistance. If you need additional support, use the Contact Us module.
Consult with fellow developers and Apple engineers on the Apple Developer Forums.
Help improve the review process or identify a need for clarity in our policies by suggesting guideline changes.β
Could you please provide clarification on whether WatchOS currently supports the real-time or on-demand measurement of skin temperature and ambient temperature? If so, Could you also guide us on the relevant APIs or resources available for incorporating these features into out applications?
Hello, We are currently developing a healthcare app using React Native and have successfully implemented the feature to fetch data such as step count, weight, blood pressure, and heart rate from HealthKit.
While we have no issues with the data retrieval itself, we have encountered a problem regarding the blood pressure data. In HealthKit's Heart β Blood Pressure β Data Sources & Access section, the "APPS AND SERVICES ALLOWED TO READ DATA" shows as "NONE," and there's no option within HealthKit to toggle the connection ON or OFF. Instead, the control for ON/OFF is available in the iPhone's SETTINGS β Health β Data Sources & Access, specifically for "Diastolic Blood Pressure" and "Systolic Blood Pressure".
Please note that the ability to toggle ON/OFF within HealthKit is available for step count, weight, and heart rate.
Could this issue with blood pressure data be due to the requirement of two permissions (for diastolic and systolic readings), and that's why it's not displayed correctly in HealthKit? What are the possible solutions for controlling the blood pressure data ON/OFF toggle within HealthKit?
I'm looking at a swimming workout sample and in the metadata I see:
Optional(["HKIndoorWorkout": 0, "HKSwimmingLocationType": 2, "HKAverageMETs": 10.7366 kcal/hrΒ·kg, "HKTimeZone": America/New_York])
There is no mention of the HKMetadataKeySwimmingStrokeStyle yet when I look at the workout in the Apple Fitness app, there is stroke style data.
How can I access the stroke enum?
I'm looking to access the HKMetadataKeyWeatherCondition that indicates the weather during a workout (sunny, cloudy, rain, etc.). I have accessed the workout metadata where I can see temperature and humidity but the weather enum eludes me. Any help would be appreciated.
When I record a workout with iPhone, the workout is displayed in the exercise ring. But not with iPad. A workout from iPad is recorded, it is in "Health" app history, but the exercise ring does not display it. Why is the workout not displayed on the exercise ring on iPad?
Dear Apple App Store Team,
I am reaching out to seek clarity and guidance specifically regarding the documentation requirements for submitting a research-based healthcare application on the App Store. Our development team is committed to ensuring compliance with all relevant guidelines, and we would appreciate your assistance in understanding the specific documentation needed for these applications.
As our application involves collecting data from patients for research purposes, we want to ensure that we provide the necessary documentation to support our submission. Here are the key areas for which we are seeking clarification:
Consent Documentation:
Any specific forms or templates required to demonstrate the obtaining of informed consent, especially for minors where parental consent is involved.
Research Nature, Purpose, and Duration:
Guidance on documenting and communicating the nature, purpose, and expected duration of the research to the participants.
Procedures, Risks, and Benefits:
Clarity on the documentation needed to communicate the research procedures, potential risks, and expected benefits to the participants or users.
Confidentiality and Data Handling:
Any specific documentation or information required demonstrating how confidentiality will be maintained and how data collected during the research will be handled, including any sharing with third parties.
Participant Contact Information:
Guidance on providing a point of contact for participant questions and inquiries.
Withdrawal Process Information:
Documentation needed to explain the withdrawal process for participants who choose to discontinue their involvement in the research.
Ethics Review Board Approval:
Specific requirements for providing proof of approval from an independent ethics review board, including any templates or forms that may be necessary.
Understanding these specific requirements will enable us to compile a comprehensive submission package tailored to the expectations of the App Store review process for research-based applications.
We appreciate your attention to this matter and look forward to your guidance. If there are any specific forms or templates that should accompany our submission, kindly let us know.
Thank you for your time and assistance.
Best regards,
Youcef Barkat
Hi,
I can find no way of getting HKSeriesType.heartbeat() data from the health store using my own workout app. The values captured seem to be from the irregular HRV measurements done by Apple.
There is a video showing HKHeartbeatSeriesSamples being consumed in an app but not how to capture them from the optical sensor.
The WWDC video on this https://stackoverflow.com/questions/77950041/getting-heartbeatseriessamples-in-ios-swift-healthkit-hkanchoredobjectquery at around 28 mins assumes you have written the beats from an external device - not from the optical sensor.
I have set typesToRead to be:
// Beat addition
HKSeriesType.heartbeat(),
HKQuantityType.quantityType(forIdentifier: .heartRateVariabilitySDNN)!,
// end beat addition
Why is the watch app not saving beat to beat interval series to the health store?? Failing that how can the watch app access the data itself so that it can then forward to the companion iPhone app?
Help much appreciated.
I am reading sleep data from AppleHealthKit API that have wearables connected.
Is it possible to retrieve:
If data came from wearable (e.g.--> True/False)
Wearable brand / Model (e.g. apple or Applewatch2)
Software Version (e.g. 1.3.4)
Are there specific permissions that need to be asked to retrieve source data?
When obtaining the running data of the Apple Watch in the health App, the segmented average heart rate obtained is inconsistent with the data displayed in the health App. Have you encountered it?
The edited code still has the problem of not lining up with the health app
private func fetchSleepData(for date: Date) {
let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)!
let endOfPeriod = date
let startOfPeriod = Calendar.current.date(byAdding: .day, value: -1, to: endOfPeriod)!
let predicate = HKQuery.predicateForSamples(withStart: startOfPeriod, end: endOfPeriod, options: [.strictStartDate, .strictEndDate])
let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { query, samples, error in
guard let samples = samples as? [HKCategorySample], !samples.isEmpty else {
DispatchQueue.main.async {
self.inBedTime = 0
self.coreTime = 0
self.deepTime = 0
self.remTime = 0
self.isSleepDataAvailable = false
}
print("No sleep data available for date: \(date)")
return
}
print("Fetched \(samples.count) sleep samples for date: \(date)")
var inBedTime = 0.0
var asleepTime = 0.0
var deepTime = 0.0
var remTime = 0.0
for sample in samples {
print("Sample value: \(sample.value)")
let duration = sample.endDate.timeIntervalSince(sample.startDate) / 60 // convert to minutes
switch sample.value {
case HKCategoryValueSleepAnalysis.inBed.rawValue:
inBedTime += duration
case HKCategoryValueSleepAnalysis.asleepCore.rawValue:
coreTime += duration
case HKCategoryValueSleepAnalysis.asleepDeep.rawValue:
deepTime += duration
case HKCategoryValueSleepAnalysis.asleepREM.rawValue:
remTime += duration
default:
break
}
}
DispatchQueue.main.async {
self.inBedTime = inBedTime
self.coreTime = coreTime
self.deepTime = deepTime
self.remTime = remTime
self.isSleepDataAvailable = true
}
}
healthStore?.execute(query)
}
I'm thinking about developing a workout tracking app. To avoid the issue of having to repeatedly download workouts, I want to persist some app model data like Apple does with their Fitness App. At a minimum, the HKWorkout class. Has anyone seen this done before? I'd hate to have reinvent the wheel. HKWorkout: HKSample: HKObject: NSObject.
Can you track steps on ipad 9th gen?
I have the same issues, when i use HKStatisticsCollectionQuery query user step count, there's a big difference in the number of steps I'm query before and after a minute's interval.
2023-12-17 15:45:41 steps=529
2023-12-17 15:46:52 steps=5817
2023-12-19 19:43:59 steps=2680
2023-12-19 19:44:31 steps=5554
What is causing this issue? I would like some assistance, please.
Hi,
The fitness features such as distance moved, steps, calories burned is it in HealthKit or in a different kit ? couldn't find any API in HealthKit ?
Also for example how can Apple Watch distinguish that this amount of steps was walked and not moved by a slow car or a scoter for example ?
Kindest Regards
Hi there,
I'm new here, looking for a step-by-step tutorial that will help me to achieve my first step.
https://developer.apple.com/documentation/workoutkit/customizing-workouts-with-workoutkit
downloaded the WorkoutKit sample file.
try to run, and connect to my account and team but get an error to connect a device.
Your team has no devices from which to generate a provisioning profile. Connect a device to use or manually add device IDs in Certificates, Identifiers & Profiles. https://developer.apple.com/account/
"
I logged in to my web account but didn't find any device IDs in Certificates, Identifiers & Profiles section
Hi.
is it possible to create a Custom Workout with different activity types.
I want a Custom Workout where the user first has to run and after do skiing.
Its like a little bit like SwimBikeRun but with running and Skiing.
How can i do this?
Thank you
Hello, it is discussed here https://developer.apple.com/videos/play/wwdc2023/10016/ (12:16) regarding WorkoutComposition, but unfortunately, I cannot find this class or structure in the documentation. Has this concept been removed?