HealthKit

RSS for tag

Access and share health and fitness data while maintaining the user’s privacy and control using HealthKit.

HealthKit Documentation

Posts under HealthKit tag

120 Posts
Sort by:
Post not yet marked as solved
18 Replies
3.6k Views
Hi, before installing iOS 15 our app received HKObserverQuery calls in background, which worked like a charm - the calls have reliably woken up our app in background, enabling it to process new HK data. In iOS 15 the new entitlement com.apple.developer.healthkit.background-delivery was added, being mandatory if HKObserverQuery calls should be delivered in background. Indeed, we added the entitlement to the Entitlements file and the Provisioning Profile of the app. After doing so, registering with enableBackgroundDelivery(for:frequency:withCompletion:) worked again without an error. While testing we observed that the app is not called at all. To debug, we captured system logs of an iPhone with iOS 15 - you can find them attached. syslog It can be seen that HK background delivery tries to fire, but dasd decides to not proceed because of the ApplicationPolicy. After some research we found this might be related to background modes capabilities. Thus we added "Background fetch" and "Background processing". Anyhow, this did not change the behavior. Again, this background delivery perfectly worked on iOS 14 - we did not change anything except adding the new background delivery entitlement (and the background processing entitlements in a second try). Are we missing any (new?) entitlements? Any other news in iOS 15 making further changes necessary? Is HKObserverQuery working for others in background mode? Thanks in advance for considering and best regards, Nils Notes on the logs: App was suspended at all times iPhone was unlocked from the beginning on iPhone was locked at 13:16
Posted
by Nils-B.
Last updated
.
Post not yet marked as solved
0 Replies
79 Views
Good evening. I'm working with a client who is considering building a remote fitness/workout application for iPads. Pretty straightforward - connect to a Zoom-like live fitness session with a trainer and 10-50 participants in various classes. They would like to have the ability for individuals who have Apple Watches to track (in realtime) various heath stats like heartrate, calories burned, etc... These stats would appear in the iPad app as some sort of overlay on top of the video. Is this possible? Can an app on the iPad talk to a companion app on the Apple Watch and get live data? Or do we have to jump through a bunch of hoops and integrate an iPhone somewhere in the picture here? We are new to this so apologies in advance if this is a stupid question. We just couldn't figure it out from the existing documentation that we found. Thanks for any advice.
Posted
by gibinla.
Last updated
.
Post not yet marked as solved
1 Replies
174 Views
I get data from the accelerometer (CMMotionManager) and training (HKWorkoutSession) and transfer it to the phone in real time, but at a random moment the watch falls asleep. In the info I use WKBackgroundModes: workout-processing The strap is tightened tightly, at first I thought that he was losing contact and the reason was in it. When I wrote the same functions earlier using WatchKit, there was no such problem, but now with SwiftUI there is this a problem. ` let workoutConfiguration = HKWorkoutConfiguration() workoutConfiguration.activityType = .mindAndBody workoutConfiguration.locationType = .unknown do { self.session = try HKWorkoutSession(healthStore: self.healthStore, configuration: workoutConfiguration) self.builder = self.session?.associatedWorkoutBuilder() self.builder?.dataSource = HKLiveWorkoutDataSource(healthStore: self.healthStore, workoutConfiguration: workoutConfiguration) self.session?.delegate = self self.builder?.delegate = self // timer for update state self.timerHealth = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.getHealth), userInfo: nil, repeats: true) self.session?.startActivity(with: self.startDate) self.builder?.beginCollection(withStart: self.startDate) { (success, error) in guard success else { print(error?.localizedDescription) return } } } catch { print(error.localizedDescription) return }` The timer print the current time, at a random moment the output stops and is restored only after the screen is turned on Apple's documentation write that if the workout process is enabled, the application will continues in the background, but it is not. how to set up background work? what did i miss?
Posted
by Stas3.
Last updated
.
Post not yet marked as solved
0 Replies
118 Views
Hi! I am a bit new to watchOS development and I am creating an app pretty much based on the sample workout app here: https://developer.apple.com/videos/play/wwdc2021/10009/ I am using Xcode 14.2 with simulator to develope my app and I don't have an Apple watch yet. And for my workouts in my app, I need to include oxygenSaturation & bodyTemperature as displaying data on the Metrics View. I was able to get the app complie and seems to be working except that there's no dummy data feed for oxygenSaturation & bodyTemperature like the heartrate data originally from the app tutorial. I wonder how I can set dummy data for oxygenSaturation & bodyTemperature so that I can know the app is running correctly? Any help would be very much appreciated!
Posted
by NickGu.
Last updated
.
Post not yet marked as solved
0 Replies
105 Views
I've tried building and running https://github.com/KhaosT/WatchActionButtonExample which works just fine. In my own project however even with the StartWorkoutIntent implemented as per https://developer.apple.com/documentation/appintents/actionbuttonarticle the option for my app in the action button settings never appears, in the simulator or on a test device. I've made sure WKBackgroundModes includes workout-processing and have fully implemented a StartWorkoutIntent (both a real implementation and also tried it with a dummy implementation from the KhaosT/WatchActionButtonExample repo). Despite all this I still can't get my app to appear in the action button settings screen. Is there anything I can do to further debug this? Has anyone else run into a similar issue? I've just spent the entire day trying to make this work...
Posted Last updated
.
Post not yet marked as solved
4 Replies
2.2k Views
I used "x-apple-health://" to open up the health app, but I want to open the Health App Sources and my app, so that my users can find the healthkit authorizations for my app. I tried "x-apple-health://Sources/MyAppName/", but it did not work. Let me know what you think I can do. Thanks
Posted
by wpenn.
Last updated
.
Post not yet marked as solved
0 Replies
118 Views
Hi iOS developers, We as a company are creating a healthcare product, and on mobile side we integrated HealthKit to get measurements. Now we are trying to integrate the app on apple watch to get Heart Rate, Blood oxygen, and other measurements that user can measure with watch. My question is, is there any clear way to trigger Apple watch sensors to make a measurement and pass them real time on the mobile app? Thank you in advance, Solaborate
Posted Last updated
.
Post not yet marked as solved
0 Replies
158 Views
Is there a list which workout types on Apple Watch record the route during workout and store it in Health? Looking at the HKWorkoutActivityType enum I know the following do record a route: walking (if it is outdoor) running (if it is outdoor) wheelchairWalkPace wheelchairRunPace cycling hiking swimming (if it is outdoor) swimBikeRun I can imagine skiing and snowboarding would also record the route? Maybe surfing, sailing, rowing and skating as well?
Posted
by andre07.
Last updated
.
Post not yet marked as solved
1 Replies
199 Views
I have requested the access from the HealthKit by below code let calorieCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)! and it working perfectly but not able to read the data using Query after reading the documentation I have found out HKStatisticsQuery is used for Query     func CaloriesBurned() {         let activeEnergy = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned)!         let startDate = Calendar.current.date(byAdding: .day,value: -7, to: Date())         let predicate = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: .strictStartDate)         let query = HKStatisticsQuery(quantityType: activeEnergy, quantitySamplePredicate: predicate,completionHandler: <#T##(HKStatisticsQuery, HKStatistics?, Error?) -> Void#>))     } but I don't understand what should be written in completion handler in above code to read the active Energy Burned I have read already documentation if anyone has sample code to read energy burned or sample code on how to use HKStatisticsQuery
Posted Last updated
.
Post marked as solved
3 Replies
336 Views
below is my code of reading data from HealthKit for Multiple Data but for reading Multiple data using Set() it shows "Cannot convert value of type 'Set' to expected argument type 'HKQuantityType' " func readData(completion: @escaping (HKStatisticsCollection?)-> Void){         let stepCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!         let MoveCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.appleMoveTime)!         let DistanceCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!         let Activitysummary = Set([stepCount,MoveCount,DistanceCount])                  let startDate = Calendar.current.date(byAdding: .day, value: -7, to: Date())         //MARK: here we setting our start time at 12.00 AM         let anchorDate = Date.monday12AM()         //MARK: we going to calculate the value for each day         let daily = DateComponents(day : 1)         let predicate = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: .strictStartDate)         //MARK: .cummulativesum -> iPhone and Apple Watch Difference         query =  HKStatisticsCollectionQuery(quantityType: Activitysummary, quantitySamplePredicate: predicate,options: .cumulativeSum, anchorDate: anchorDate, intervalComponents: daily) //MARK: here in ActivitySummary it show the error                  query!.initialResultsHandler = { query,statisticsCollection, error in             completion(statisticsCollection)         }         if let healthStore = healthStore, let query = self.query{             healthStore.execute(query)         }     }
Posted Last updated
.
Post not yet marked as solved
0 Replies
223 Views
I am working with a BLE peripheral that tracks heart rate. I can sync the data to HealthKit when the app is running and it is working fine. I would like to send the heart rate to HealthKit without user opening the app. It is mentioned in the documentation that the direct import of data is possible from Bluetooth LE heart rate monitors to HealthKit.  Link : https://developer.apple.com/documentation/healthkit/hksource?language=objc Any help would be greatly appreciated.
Posted
by Shemona.
Last updated
.
Post not yet marked as solved
0 Replies
207 Views
Hello, Our app currently collects the number of steps from our app users' smartwatches. (Limited to users who have insurance policy for a certain product) If the app were to no longer exist, how can I directly collect data of the users (based on personal information) from HealthKit?
Posted Last updated
.
Post not yet marked as solved
0 Replies
257 Views
Is it possible to trigger SPO2 measurements programmatically more frequently than once per 15 minutes? For example, once per 1 minute? It is possible with manual measurements in "Blood Oxygen" app, but it would be helpful to find the way to do that programmatically.
Posted
by msharhan.
Last updated
.
Post not yet marked as solved
0 Replies
282 Views
I have used below source code to get the steps from HealthKit. It's working fine many users but few users face the issue regards to get the steps from HealthKit in the our Application. After tracking the logs that issue found **: Error Domain=com.apple.healthkit Code=3 "Unable to invalidate interval: no data source available." ** Please help to know what exactly issue in the below source code. -(void) HealthKitSteps {     HKHealthStore *healthStore = [[HKHealthStore alloc] init];     NSCalendar *calendar = [NSCalendar currentCalendar];     [calendar setTimeZone:[NSTimeZone localTimeZone]];     NSDateComponents *interval = [[NSDateComponents alloc] init];     interval.hour = 2;   NSDateComponents *anchorComponents = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];     anchorComponents.hour = 0;     NSDate *anchorDate = [calendar dateFromComponents:anchorComponents];     HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"metadata.%K != YES", HKMetadataKeyWasUserEntered];     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{     HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:nil options:HKStatisticsOptionCumulativeSum anchorDate:anchorDate intervalComponents:interval];     // Set the results handler     query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *results, NSError *error) {         if (error) {             // Perform proper error handling here             [UIUtils NSLogFunction:[NSString stringWithFormat:@"*** An error occurred while calculating the statistics: %@ ***",error.localizedDescription] dict:nil];         }         else         {             NSDate* sourceDate = [NSDate date];             NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:0 sinceDate:sourceDate];             NSDateFormatter *endDateFormatter = [[NSDateFormatter alloc] init];             [endDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];             [endDateFormatter setTimeZone:[NSTimeZone localTimeZone]];                          NSString* localTime = [endDateFormatter stringFromDate:destinationDate];             NSDate* endDate = [endDateFormatter dateFromString:localTime];                          NSDateFormatter *objDateFormatter = [[NSDateFormatter alloc] init];             [objDateFormatter setDateFormat:@"yyyy-MM-dd"];             [objDateFormatter setTimeZone:[NSTimeZone localTimeZone]];                          NSDate *startDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:-self->diffDaysFromLastSync toDate:endDate options:0];                          NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];             [calendar setTimeZone:[NSTimeZone localTimeZone]];             NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:startDate];             [components setTimeZone:[NSTimeZone localTimeZone]];             [components setHour:0];             startDate = [calendar dateFromComponents:components];                          NSLog(@"Healthkit : startDate : %@ endDate : %@",[endDateFormatter stringFromDate:startDate],[endDateFormatter stringFromDate:endDate]);                          [results enumerateStatisticsFromDate:startDate toDate:endDate withBlock:^(HKStatistics *result, BOOL *stop) {             HKQuantity *quantity = result.sumQuantity;                 if (quantity) {                     double value = [quantity doubleValueForUnit:[HKUnit countUnit]];                     NSString *count = [NSString stringWithFormat:@"%.f",value];                     NSString *dateOfCount  = [objDateFormatter stringFromDate:[result startDate]];                     NSString* dateTime = [endDateFormatter stringFromDate:[result startDate]];                     NSLog(@"results quantity start Date %@ sum %@ Count %@",result.startDate, result.sumQuantity,count);                 }                 else                 {                     NSLog(@"results not found");                 }             }];         }     };     [healthStore executeQuery:query];     }); }
Posted
by RahulS.
Last updated
.
Post not yet marked as solved
0 Replies
256 Views
Hey All, So sorry if this is a stupid question, but I was wondering, is there a way to update a users fitness/health ring goals via the API? Also, am I able to update and save custom workout templates via the API? Many thanks, in advance. P
Posted
by ph1l88.
Last updated
.