Post not yet marked as solved
When I finish Running on AppleWatch, I can see the value of average cadence on Apple Watch's Workout App and iPhone's Fitness App, but I can't find any APIs about that value.However I'm not sure how does Fitness App calculated, I tried to get step count from HealthKit, and calculated the value, but the value is different from Apple's. Can you tell me how to get it correctly and accurately?
Post not yet marked as solved
Hi, I have a problem with HealthKit. When fetching sleepAnalysis, instead of getting a record for every night, I get multiple records for each night. How can I calculate the total amount of time for every day from the startDate and the endDate of every record? Thanks.
Post not yet marked as solved
As per apple documentation I go through them, after surfing I didn't get any of the basic implementation for electrocardio gram steps:
Request Permission.
Reading the values for data points.
Sample query.
Also need to understand, how this is different from HKCategoryTypeIdentifier/HKQuantityTypeIdentifier.
As in other heakthdata points the above identifier is used to formulate the data point accessing and reading and adding into our local storage.
Any sugesstion please.
I have suspected there is something wrong with my personal Health account for a while but while working on a new app that queries HealthKit I'm pretty certain.
I've developed a very simple health app where you can request auth to read steps and then runs a statistic collection query to get a tally of steps you take.
This test app runs on the simulator fine. But when I run it on a device using my Apple ID the query just hangs. I don't get the callback for the initial result or the updated results.
Looking in Xcode, the memory graph just steadily increases until you terminate the app. And it appears there are millions of statistics objects being created.
Can anyone suggest anything to prevent this from happening? Do I need to reset my Health data? I would rather there was another solution.
I've included the code for this dummy app below. You will need to add HealthKit capabilities and the Privacy: Health Sharing info key for it to run.
import SwiftUI
import HealthKit
@main
struct StepCountApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class ViewModel: ObservableObject {
let healthStore = HKHealthStore()
var query: HKStatisticsCollectionQuery?
@Published var isQuerying = false
@Published var authStatus: HKAuthorizationStatus = .notDetermined
@Published var stepCount: Int = 0
init() {
}
func updateAuthStatus() {
authStatus = healthStore.authorizationStatus(for: .quantityType(forIdentifier: .stepCount)!)
}
func requestAuth() {
let sharing = Set<HKSampleType>()
let reading = Set<HKObjectType>([.quantityType(forIdentifier: .stepCount)!])
healthStore.requestAuthorization(toShare: sharing, read: reading) { [weak self] result, error in
if result {
DispatchQueue.main.async {
self?.updateAuthStatus()
}
} else if let error = error {
print("Auth failed: \(error.localizedDescription)")
} else {
fatalError("How did we get here?")
}
}
}
func stopQuery() {
guard let query = query else { return }
healthStore.stop(query)
self.query = nil
isQuerying = false
}
func startQuery() {
let stepsType = HKObjectType.quantityType(forIdentifier: .stepCount)!
let intervalComponents = DateComponents(day: 1)
query = HKStatisticsCollectionQuery(
quantityType: stepsType,
quantitySamplePredicate: nil,
options: [.cumulativeSum],
anchorDate: Date(),
intervalComponents: intervalComponents
)
query!.initialResultsHandler = { [weak self] query, results, error in
print("Initial result")
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let statisticsCollection = results else {
print("Error: No stats collection")
return
}
guard let statistics = statisticsCollection.statistics(for: Date()) else {
print("Error: No stats for date")
return
}
let sum = statistics.sumQuantity()?.doubleValue(for: .count()) ?? 0
DispatchQueue.main.async {
self?.stepCount = Int(sum)
}
}
query!.statisticsUpdateHandler = { [weak self] query, statistics, results, error in
print("Updated result")
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let statisticsCollection = results else {
print("Error: No stats collection")
return
}
guard let statistics = statisticsCollection.statistics(for: Date()) else {
print("Error: No stats for date")
return
}
guard let sum = statistics.sumQuantity()?.doubleValue(for: .count()) else {
print("Error: Statistics have no data?")
return
}
DispatchQueue.main.async {
DispatchQueue.main.async {
self?.stepCount = Int(sum)
}
}
}
healthStore.execute(query!)
isQuerying = true
}
var authStatusString: String {
switch authStatus {
case .notDetermined: return "Not determined"
case .sharingAuthorized: return "Sharing authorised"
case .sharingDenied: return "Sharing denied"
@unknown default: fatalError()
}
}
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
Form {
Section {
HStack {
Text("Auth Status")
Spacer()
Text("\(viewModel.authStatusString)")
}
}
Section {
Button("Request Auth") {
viewModel.requestAuth()
}
}
Section {
if viewModel.isQuerying {
Button("Stop query") {
viewModel.stopQuery()
}
} else {
Button("Start query") {
viewModel.startQuery()
}
}
}
Section {
HStack {
Text("Step count")
Spacer()
Text("\(viewModel.stepCount)")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
We have enable HK background sync and it works great, every time there is a new object in HK, the app gets the object and we post the object to the server etc.
The problem is that every time the HKObserverQuery(sampleType: sampleType, predicate: nil) is called due to a new HK object, we are also getting the didFinishWithOptions method in the app delegate to be called.
The problem here is that when didFinishWithOptions is called we fetch user details, fetch a bunch of data from the server and make lots of tasks.
Is there a way to know if the app is being launched because of a HK background sync task or because the user launched the app?
Or best practice recommendation to not start every single task in the app we trigger on regular launches just for a HK import?
Thank you
Post not yet marked as solved
With this I can open Apple health:
“x-apple-health://“
but I’d like to open the page that contains myApp’s privacy settings.
Apple health settings>Privacy>Apps
Is there a way to go to this particular page in HealthKit?
Post not yet marked as solved
Hi,
I have noticed some drastic changes in some of the calculations/metrics that I get out of the Apple Health Apps since updating to the iOS15 Beta and WatchOS 8 Beta.
Let me preface this by saying there have been no changes to my health or workouts, way I use the watch or phone since updating.
For instance, my V02 max which has been in the 36-38 range for nearly two years suddenly dropped to 32-33 range since the update.
The Blood Oxygen measurements as well have been much more erratic - I am usually in the 97-100% range, but since updating I have been anywhere from 90-100, and if I take two measurements right after each other I might get one @ 90 and one at 100.
Thanks,
Remy
Post not yet marked as solved
I'm trying to get all samples after a given startDate and have that query running for as long as the app is "alive" including background.
I used
let predicate = HKQuery.predicateForSamples(withStart: queryStart, end: nil, options: HKQueryOptions.strictStartDate)
I thought: if its not specified it cannot be restricting…
From the results I am getting I infer that it's using the end of the day the query is executed as a restriction:
I am getting all updates the same day with the samplesUpdatequeryResultshandler but the next morning my app doesn't receive samples unless I restart it.
Edit: I should mention I am using options: HKQueryOptions.strictStartDate
Is it too much to ask that the documentation mention how nil is handled if it's allowed? One could omit the ? and everyone would know to specify the end date.
I'll now use
let queryEndDate = Calendar.current.date(byAdding: .year, value: 10, to: Date())!
See how that goes.
Post not yet marked as solved
Hi,
I'm developing an application that would like to sync my vitals stats from my Apple Watch.
So is there anyway to get vitals (like SPO2) directly from my Apple Watch? Does HealthKit help this?
Thank you.
Post not yet marked as solved
I'm a researcher working for children with special needs such as ADHD. With my research group, we would like to use the Apple Smartwatch as a monitoring device in several health-related research projects. However, before buying a lot of devices, I need clear and detailed information about the accessibility of SpO2, EDA, ECG, and temperature raw data through the Apple watch.
Will I be able to access raw data to embed in my customised app?
If I need to develop an app that reads and processes through custom algorithms raw data coming from these sensors, is it possible?
I just want clear and detailed information before buying a lot of devices.
Post not yet marked as solved
Hello everyone,
I'm making an app that saves rowing workouts. Rowing workouts are traditionally in meters. I want my workout summaries to always show in meters.
I have created and saved a HKWorkout instance. For the totalDistance, I am saving a quantity that uses HKUnit.meter() as its unit. Any intervals that I've associated with the workout are also saved with HKUnit.meter() as the unit.
When I look at the Workout in the Health app, it shows the total distance in miles. All the intervals are in miles as well
Is there a special piece of metadata that I need to add to my workout to hint to the Health app that I'd like to always see the summary using meters?
How can I get my workout to always be shown in meters in the health app?
Thank you for your advice,
_ michael
Post not yet marked as solved
Hi,
I coded HKObserverQuery multi time for observing ecg, high heart rate event..etc but App observe one query. Can I set multi HKObserverQuery?
Post not yet marked as solved
I know that heart rate is sent by HealthKit every 4 seconds. But what about other vital signs? Oxygen saturation, blood pressure, Glucose, respiratory rate and body temperature?
Does the emulator create only heart rate and steps data? Does it create blood pressure or oxygen saturation data?
Post not yet marked as solved
I am new to Swift development. I am building my first WatchOS app that collects motion data. I am collecting motion data using startDeviceMotionUpdates with handler. However stopDeviceMotionUpdates doesn't stop the updates and handler goes in endless loop.
class WatchMotionManager: ObservableObject {
let motion = CMMotionManager()
let queue = OperationQueue()
func startQueuedUpdates() {
motion.deviceMotionUpdateInterval = 1.0 / 50.0
motion.showsDeviceMovementDisplay = true
motion.startDeviceMotionUpdates(to: self.queue, withHandler: { (data, error) in
if let motionData = data {
//get data
}
})
}
func stopQueuedUpdates() {
self.motion.stopDeviceMotionUpdates()
}
}```
Post not yet marked as solved
I recently renewed a provisioning profile and now i'm getting the following warning (and failure when building during code signing):
warning: Provisioning profile "[redacted]" for "OneMedly" contains entitlements that aren't in the entitlements file: com.apple.developer.healthkit.background-delivery. To use these entitlements, add them to your entitlements file. Otherwise, remove unused entitlements from your provisioning profile. (in target 'OneMedly' from project 'OneMedly')
The app does use HealthKit and the provisioning profile (which apple generates) has HealthKit and if I inspect the provisioning profile, it does indeed contain this healthkit.background-delivery attribute.
This doesn't seem to be problem for debug builds, only for release builds.
Does anyone know what is causing this warning/error? Is there a workaround?
Post not yet marked as solved
I recently got an Apple Watch, and now I have lots of health data on my iPhone. I'd like to get that data onto my Mac, where I can analyze it using statistical packages like "R".
As a kludge, I can run an iPhone app in the debugger to "print" the health data as CSV records to the Xcode output, and then do a "Select All", "Copy" and "Paste" to put the data into Aquamacs, where I can save to a Mac *.csv file and access it using "R"
This is straightforward, but tedious. Does anyone have another suggestion? I've considered using CloudKit or CoreData in iCloud, but both seem like overkill. Is there any way to write a CSV file to iCloud, or to connect to a file URL on my Mac over the local network from the iPhone?
Thanks.
Post not yet marked as solved
It's been a week since I was rejected.
the things I did
a. remake Provisioning, Signing & Capabilities remove
b. info.plist remove -
NSHealthShareUsageDescription, NSHealthUpdateUsageDescription
c. search to Xcode source or HealthKit Api (Don't find): HealthKit, Health, HK..
d. Target - Build Phases - Link Binary With Libraries remove
e. pod update
but..
Metadata Rejected
Where else should I check?
Apple's message :
However, we continue to find that the previously communicated issue persist.
While you may not have intended to include HealthKit in your app, HealthKit APIs may have been included via third-party platforms implemented in your app.
Specifically, we were still able to locate HealKit-related keys.
Alternatively, HealthKit-related keys or references may have been included in your app’s Info.plist, including but not limited to:
/System/Library/Frameworks/HealthKit.framework/HealthKit
Next Steps
To resolve this issue, please remove all HealthKit APIs from your app, as well as any references to HealthKit keys from the info.plist entirely.
Post not yet marked as solved
Hello Team,
We are Testing Health Records feature into our Patient Application. We have imported sample data available in Simulator and modelling it using FHIR Model. We are trying to group test results based on Origin(Lab Name and Result Date) of Lab Reports. But we are not able to retrieve Lab Name and Lab Test Panel Mapping information.
Post not yet marked as solved
Hello everyone,
I am in the process of building an app that gives the user more statistical information about their sleep, and I would like to access the sleep duration goal and the sleep schedule that the user can set in the Health app.
Is it possible to access this information and if so, how do I do that? You are welcome to point me to the specific documentation, I just can't find anything about this in the documentation.
Have a nice day,
Simon