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

How to add HKQuantity to HKWorkout with WorkoutBuilder
At the moment I am working on a running app for the iPhone. One issue that I have is, that I am building the HKWorkout using the HKWorkoutBuilder according to Apples Documentation - https://developer.apple.com/documentation/healthkit/hkworkoutbuilder. But I am not able to associate the totalDistance with the workout – mentioned here in the Documentation - https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/adding_samples_to_a_workout. totalDistance is nil when I try to read it from the workout – no surprise. I think I miss something here. Thanks in advance.
3
0
1.4k
Sep ’22
Queried heart rate samples in the past interval have lower resolution than recent samples
I am querying heart rate samples taken during a workout. For all of the mentioned cases below I'm wearing an Apple Watch and using the stock Workouts.app in the watch. If I query heart rate samples for a recent workout, it being yesterday or the past month for example, I get the full samples. If I query a workout let's say, two/three months in the past the samples I get back look "choppy" with a lot of missing data. (See attached image) imgur.com/a/FbMSBoa How am I getting the heart rate samples? swift extension HKHealthStore: HKHealthStoreCombine {     public func getT(sample: T, start: Date, end: Date, limit: Int = HKObjectQueryNoLimit) - AnyPublisher[HKQuantitySample], Error where T: HKObjectType {         let subject = PassthroughSubject[HKQuantitySample], Error()                 let sampleType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: sample.identifier))!         let predicate = HKQuery.predicateForSamples(withStart: start, end: end)                  let query = HKSampleQuery(sampleType: sampleType, predicate: predicate, limit: limit, sortDescriptors: nil, resultsHandler: { (query, samples, error) in             guard error == nil else {                 logger.error("Error fetching samples of type \(sample.description) from \(start) to \(end) with a limit of \(limit): \(error!.localizedDescription)")                 subject.send(completion: .failure(error!))                 return             }             let samples = samples as? [HKQuantitySample] ?? []             logger.log("Successfully fetched \(samples.count) samples of type \(sample.description) from \(start) to \(end) with a limit of \(limit)")             subject.send(samples)             subject.send(completion: .finished)         })         self.execute(query)         return subject.eraseToAnyPublisher()     } } swift healthStore.get(sample: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!, start: workout.startDate, end: workout.endDate)             .map({                 $0.compactMap({ $0.quantity.doubleValue(for: UserUnits.shared().heartCountUnits) })             })             .replaceError(with: [])             .receive(on: DispatchQueue.main)             .sink(receiveValue: {                 self.heartRate = $0             })             .store(in: &bag) Is this some kind of wrong way that I am working with HealthKit? I don't know what the issue can be but it looks like accessing heart samples in the "past" are somewhat archived and I don't get the full resolution.
4
0
2.1k
Oct ’21
How to get Workout's average cadence
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?
1
1
1.4k
Apr ’22
Customizing the "Return to App" option on the apple watch
Hey guys, I'm trying to create a custom swimming app, and I'd like to add the "When in Session" > "Return to App" option to my app (under settings > general > wake screen > [app name], like the workout app has). Otherwise, the moment I put my watch under water it goes back to the default clock app, when I raise to wake... would anyone happen to know how to do that? Sorry if it's a super obvious answer lol...
1
0
977
Aug ’21
Can't run Research and Care App (WWDC Code Along)
Hello everyone, I just started watching the WWDC21 Code Along "Build a Research and Care App, Part 1" and wanted to run the project in Xcode. However, when I clone the Repo with the recommended git clone --recurse-submodule https://github.com/carekit-apple/WWDC21-RecoverApp.git command and open the project, I get the following error: /WWDC21-RecoverApp/Recover Part 1/Recover.xcodeproj This Copy Files build phase contains a reference to a missing file 'ResearchKit.framework'. /WWDC21-RecoverApp/ResearchKit only contains 2 files (CONTRIBUTING.md and LFS-Files). I was wondering how I could get the project up and running and if there are additional steps to take, that I didn't see in the presentation / Github Readme. Thanks!
3
0
2.2k
Jun ’23
HKStatisticsQuery returns "authorization not determined" error.
Hello. We have a problem with HealthKit. The HKStatisticsQuery returns an error saying "authorization not determined", even though I have allowed to retrieve the number of steps on the health care screen and with requestAuthorization function. A part of the source code is shown below. let type = HKSampleType.quantityType(forIdentifier: .stepCount)! let datePredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate)       let statisticsQuery = HKStatisticsQuery( quantityType: type, quantitySamplePredicate: datePredicate, options: .separateBySource ) { (query, data, error) in    if let _error = error {      // We're going through here. } } It does not always reproduce, but rarely does. Reinstalling does not cure it. The condition for recovery is unknown, but the situation seems to be changing every day of the week. This may be due to the lack of walking data on particular day. Does anyone know the cause of this? Thanks.
2
0
699
Jul ’21
Fitness total calories do not match the sum total of Active Energy Burned + Basal Energy Burned from health kit
Hi, First of all, thank you for taking the time to look over my question I'd really appreciate any feedback. My question is regarding how Apple calculates their total calories on the fitness app. This would be shown in the "Move" section under the graph where it would say "TOTAL _____ CAL". From researching online we could only find that Apple gets total calories from adding Active Energy Burned + Basal Energy Burned ( gathered from health kit ). While implementing this calculation in our app, we noticed that our total calories calculation are off from the fitness app by 300-500 calories. We are collecting the Active Energy Burned & Basal Energy burned from Apple Health Kit and adding that up to get our total calories burned. I'd like to know if we are missing something from this calculation, if we are missing something from health kit that we need to add into this equation, or its some type of configuration problem with our apple/watch/data? Thank you once again for your help!
0
0
715
Jul ’21
Is any sample or demo example for Electrocardiogram Health Data Point?
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.
1
0
606
Jul ’21
Identify Dexcom CGM data from Apple health
I want to identify all sample data which one coming from Dexcom CGM applications. I can use HKSourceRevision but if that so i need to put filtration for all bundle id which one belongs from CGM,Since we are not sure if they have more applications on later stage then again, we need to add it from code level. let query = HKSourceQuery(sampleType: type,samplePredicate: predicate) { query, sources, error in   let desiredSources = sources?.filter {!$0.bundleIdentifier.starts(with: "com.cgmbundleid")} let sourcePredicate = HKQuery.predicateForObjects(from: desiredSources!)     } Any other way to identify the data from Dexcom CGM which one synched to apple health.
0
0
477
Jul ’21
HealthKit query hangs and consumes vast amounts of memory on device only.
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() } }
2
0
1.6k
Jul ’21
HKBackgroundSync Launching app and draining Battery
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
1
0
533
Aug ’21
Did iOS15 / WatchOS8 bring Health "Calculation" Changes?
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
0
0
687
Aug ’21
HKQuery.predicateForSamples - how is endDate: nil interpreted
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.
0
0
1.1k
Aug ’21
How to add HKQuantity to HKWorkout with WorkoutBuilder
At the moment I am working on a running app for the iPhone. One issue that I have is, that I am building the HKWorkout using the HKWorkoutBuilder according to Apples Documentation - https://developer.apple.com/documentation/healthkit/hkworkoutbuilder. But I am not able to associate the totalDistance with the workout – mentioned here in the Documentation - https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/adding_samples_to_a_workout. totalDistance is nil when I try to read it from the workout – no surprise. I think I miss something here. Thanks in advance.
Replies
3
Boosts
0
Views
1.4k
Activity
Sep ’22
Queried heart rate samples in the past interval have lower resolution than recent samples
I am querying heart rate samples taken during a workout. For all of the mentioned cases below I'm wearing an Apple Watch and using the stock Workouts.app in the watch. If I query heart rate samples for a recent workout, it being yesterday or the past month for example, I get the full samples. If I query a workout let's say, two/three months in the past the samples I get back look "choppy" with a lot of missing data. (See attached image) imgur.com/a/FbMSBoa How am I getting the heart rate samples? swift extension HKHealthStore: HKHealthStoreCombine {     public func getT(sample: T, start: Date, end: Date, limit: Int = HKObjectQueryNoLimit) - AnyPublisher[HKQuantitySample], Error where T: HKObjectType {         let subject = PassthroughSubject[HKQuantitySample], Error()                 let sampleType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: sample.identifier))!         let predicate = HKQuery.predicateForSamples(withStart: start, end: end)                  let query = HKSampleQuery(sampleType: sampleType, predicate: predicate, limit: limit, sortDescriptors: nil, resultsHandler: { (query, samples, error) in             guard error == nil else {                 logger.error("Error fetching samples of type \(sample.description) from \(start) to \(end) with a limit of \(limit): \(error!.localizedDescription)")                 subject.send(completion: .failure(error!))                 return             }             let samples = samples as? [HKQuantitySample] ?? []             logger.log("Successfully fetched \(samples.count) samples of type \(sample.description) from \(start) to \(end) with a limit of \(limit)")             subject.send(samples)             subject.send(completion: .finished)         })         self.execute(query)         return subject.eraseToAnyPublisher()     } } swift healthStore.get(sample: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!, start: workout.startDate, end: workout.endDate)             .map({                 $0.compactMap({ $0.quantity.doubleValue(for: UserUnits.shared().heartCountUnits) })             })             .replaceError(with: [])             .receive(on: DispatchQueue.main)             .sink(receiveValue: {                 self.heartRate = $0             })             .store(in: &amp;bag) Is this some kind of wrong way that I am working with HealthKit? I don't know what the issue can be but it looks like accessing heart samples in the "past" are somewhat archived and I don't get the full resolution.
Replies
4
Boosts
0
Views
2.1k
Activity
Oct ’21
ActiveEnergyBurned or Calories Burned API for iOS?
I am looking for a API for iOS that calculates ActiveEnergyBurned or Calories burned for my iOS app. I want the api to calculate as close to Apple Watch as possible.
Replies
1
Boosts
0
Views
1.1k
Activity
Dec ’21
How to get Workout's average cadence
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?
Replies
1
Boosts
1
Views
1.4k
Activity
Apr ’22
Customizing the "Return to App" option on the apple watch
Hey guys, I'm trying to create a custom swimming app, and I'd like to add the "When in Session" > "Return to App" option to my app (under settings > general > wake screen > [app name], like the workout app has). Otherwise, the moment I put my watch under water it goes back to the default clock app, when I raise to wake... would anyone happen to know how to do that? Sorry if it's a super obvious answer lol...
Replies
1
Boosts
0
Views
977
Activity
Aug ’21
Can't run Research and Care App (WWDC Code Along)
Hello everyone, I just started watching the WWDC21 Code Along "Build a Research and Care App, Part 1" and wanted to run the project in Xcode. However, when I clone the Repo with the recommended git clone --recurse-submodule https://github.com/carekit-apple/WWDC21-RecoverApp.git command and open the project, I get the following error: /WWDC21-RecoverApp/Recover Part 1/Recover.xcodeproj This Copy Files build phase contains a reference to a missing file 'ResearchKit.framework'. /WWDC21-RecoverApp/ResearchKit only contains 2 files (CONTRIBUTING.md and LFS-Files). I was wondering how I could get the project up and running and if there are additional steps to take, that I didn't see in the presentation / Github Readme. Thanks!
Replies
3
Boosts
0
Views
2.2k
Activity
Jun ’23
HKStatisticsQuery returns "authorization not determined" error.
Hello. We have a problem with HealthKit. The HKStatisticsQuery returns an error saying "authorization not determined", even though I have allowed to retrieve the number of steps on the health care screen and with requestAuthorization function. A part of the source code is shown below. let type = HKSampleType.quantityType(forIdentifier: .stepCount)! let datePredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate)       let statisticsQuery = HKStatisticsQuery( quantityType: type, quantitySamplePredicate: datePredicate, options: .separateBySource ) { (query, data, error) in    if let _error = error {      // We're going through here. } } It does not always reproduce, but rarely does. Reinstalling does not cure it. The condition for recovery is unknown, but the situation seems to be changing every day of the week. This may be due to the lack of walking data on particular day. Does anyone know the cause of this? Thanks.
Replies
2
Boosts
0
Views
699
Activity
Jul ’21
Get Oxygen saturation measurement every 10 minutes in Apple Watch
I'm developing an application and I need to get the Oxygen saturation measurement every 10 minutes. Is it possible to get the saturation measurement every 10 min?
Replies
0
Boosts
0
Views
591
Activity
Jun ’21
Storing HealthKit data in cloud server
I'm developing a fitness-related platform can I store HK user's data in a cloud server? The idea is to allow users to retrieve their health info from the web application
Replies
0
Boosts
0
Views
430
Activity
Jul ’21
Fitness total calories do not match the sum total of Active Energy Burned + Basal Energy Burned from health kit
Hi, First of all, thank you for taking the time to look over my question I'd really appreciate any feedback. My question is regarding how Apple calculates their total calories on the fitness app. This would be shown in the "Move" section under the graph where it would say "TOTAL _____ CAL". From researching online we could only find that Apple gets total calories from adding Active Energy Burned + Basal Energy Burned ( gathered from health kit ). While implementing this calculation in our app, we noticed that our total calories calculation are off from the fitness app by 300-500 calories. We are collecting the Active Energy Burned & Basal Energy burned from Apple Health Kit and adding that up to get our total calories burned. I'd like to know if we are missing something from this calculation, if we are missing something from health kit that we need to add into this equation, or its some type of configuration problem with our apple/watch/data? Thank you once again for your help!
Replies
0
Boosts
0
Views
715
Activity
Jul ’21
HealthKit total sleep time
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.
Replies
2
Boosts
0
Views
2.2k
Activity
Feb ’22
Is any sample or demo example for Electrocardiogram Health Data Point?
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.
Replies
1
Boosts
0
Views
606
Activity
Jul ’21
Identify Dexcom CGM data from Apple health
I want to identify all sample data which one coming from Dexcom CGM applications. I can use HKSourceRevision but if that so i need to put filtration for all bundle id which one belongs from CGM,Since we are not sure if they have more applications on later stage then again, we need to add it from code level. let query = HKSourceQuery(sampleType: type,samplePredicate: predicate) { query, sources, error in   let desiredSources = sources?.filter {!$0.bundleIdentifier.starts(with: "com.cgmbundleid")} let sourcePredicate = HKQuery.predicateForObjects(from: desiredSources!)     } Any other way to identify the data from Dexcom CGM which one synched to apple health.
Replies
0
Boosts
0
Views
477
Activity
Jul ’21
Confused about carekit and researchkit
Hi, I have to develop an app to let the patients record a 20-30 seconds long video, upload it and show them some insights about it. I know that both carekit and researchkit support charts to provide insights but which one of them will allow me to show a view controller to record the video? Thanks for your time.
Replies
0
Boosts
0
Views
809
Activity
Jul ’21
HealthKit query hangs and consumes vast amounts of memory on device only.
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() } }
Replies
2
Boosts
0
Views
1.6k
Activity
Jul ’21
HKBackgroundSync Launching app and draining Battery
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
Replies
1
Boosts
0
Views
533
Activity
Aug ’21
What is the URL to open Apple health settings>privacy>apps>“myApp”
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?
Replies
0
Boosts
1
Views
686
Activity
Jul ’21
Did iOS15 / WatchOS8 bring Health "Calculation" Changes?
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
Replies
0
Boosts
0
Views
687
Activity
Aug ’21
HKQuery.predicateForSamples - how is endDate: nil interpreted
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.
Replies
0
Boosts
0
Views
1.1k
Activity
Aug ’21
How to get SPO2 directly from Apple Watch
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.
Replies
1
Boosts
0
Views
639
Activity
Aug ’21