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

105 Posts
Sort by:
Post not yet marked as solved
3 Replies
1.3k Views
We seem to be dealing with a weird issue where the clinical health records entitlement keeps on getting added into our final embedded.mobileprovision when we prepare a build for distribution. We seem to get this in the final package. <key>com.apple.developer.healthkit.access</key> <array> <string>health-records</string> </array> But in our projects entitlement file there is no reference to health records. Below is the raw values inside of this file. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>aps-environment</key> <string>development</string> <key>com.apple.developer.healthkit</key> <true/> <key>com.apple.developer.healthkit.access</key> <array/> <key>com.apple.security.application-groups</key> <array> <string>group.xxxxx</string> </array> </dict> </plist> And also in the project this isn't selected in the capabilities section either. Has anyone come across this issue before where Xcode automatically adds clinical records even though you haven't selected the checkbox.
Posted
by
Post not yet marked as solved
2 Replies
1.6k Views
When I try to add HealthKit capabilities to my app, I get the following signing errors: Communication with Apple failed. Your account does not have sufficient permissions to modify containers. Provisioning profile "iOS Team Provisioning Profile: com.domain.app" doesn't support the HealthKit capability. Provisioning profile "iOS Team Provisioning Profile: com.domain.app" doesn't include the com.apple.developer.healthkit and com.apple.developer.healthkit.access entitlements. In my developer account, the HK capability is enabled. And the entitlements needed are automatically generated by Xcode when I add HK capability, if I try to add them, it says they're already there. I have automatically managed signing selected. Clinical health records are not enabled for Health Kit. Common solutions like cleaning, derived data, and restarts don't help. Does anybody know what this is?
Posted
by
Post not yet marked as solved
20 Replies
6.2k 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
Post not yet marked as solved
2 Replies
2.2k Views
Exciting to see the new Medication tracking features coming to Health. As a medical app we're wondering if read/write access to these is coming to HealthKit? We're currently building prescription management into our app so it would be great to be able to let users also add these to Health to handle their adherence tracking.
Posted
by
Post not yet marked as solved
2 Replies
1.7k Views
I developed an iPhone/Watch app with the single target setting (new method) for Watch app projects, which will be available from Xcode14. This app uses HealthKit to retrieve information such as step count and heart rate from healthcare. The watch app is not independent and requires the iPhone app (companion app). Regarding the permission to access health care, i found some differences from the Old WatchApp Project (application project structure using WatchExtension when Xcode 13.4 or lower is used). This does not occur in the iPhone simulator or watch simulator, but only on the actual device. Both the iPhone app and watch app now display a dialog to allow access to health care In the Old WatchApp Project, if access was granted in either app, the granted access is synchronized. When checking the Health Care access status in the iPhone Settings App, permission settings for both the iPhone app and watch app are displayed independently. Because each permission setting is independent, you can choose to allow access to the iPhone app but not to allow it to the watch app. the Old WatchApp Project, permission settings for the iPhone app and watch app were synchronized, so it was not possible to have different settings for each. These behaviors are not described in the documentation. It would be understandable if the transition from watch "extension" to watch "app" is to split the app into two separate units. However, since there is no official documentation explaining this, i cannot determine whether this is the correct specification or not. Furthermore, since the companion app is required rather than a separate Watch app, having the Health Care permission settings out of sync with the companion app could cause unexpected problems and worsen the user experience. (It would be difficult and cumbersome for the user to know what settings they have made). Is there a solution to synchronize this behavior with the companion app like as the Old WatchApp Project? Do i have to go back to the project configuration (use of watchExtension) before Xcode13? I have prepared a sample project below that can test the above. https://github.com/HayakawaAKIRA/SingleTargetWatchOSApp-HealthKit reference: https://developer.apple.com/videos/play/wwdc2022/10133/ https://developer.apple.com/documentation/watchkit/wkapplication https://developer.apple.com/documentation/healthkit/setting_up_healthkit
Post not yet marked as solved
1 Replies
782 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
Post not yet marked as solved
1 Replies
839 Views
I'm looking to display the workouts performed similar to what Apple Fitness displays. However, I want to get traditional strength training and functional strength training workouts particularly. I would also like to get the number of workouts performed within the week. I'm having issues reading the data and displaying it. Below is the code I'm using. I'm omitting the authorization method because I have that with other health variables I'm getting. Also, when I try to get the workoutActivity type to display, nothing is showing up. I've looked over apple's healthkit documentation but getting a big confused/lost as a beginner, particularly with the workout data. I've attached pictures as a reference on what I would like to accomplish var selectedWorkoutQuery: HKQuery? @Published var muscleStrength: [HKWorkout] = [HKWorkout]() func getStrengthTrainingWorkouts() { let date = Date() let startDate = Calendar.current.dateInterval(of: .weekOfYear, for: date)?.start let datePredicate = HKQuery.predicateForSamples(withStart: startDate, end: nil, options: .strictStartDate) let traditionalStrengthTrainingPredicate = HKQuery.predicateForWorkouts(with: .traditionalStrengthTraining) let functionalStrengthTrainingPredicate = HKQuery.predicateForWorkouts(with: .functionalStrengthTraining) let strengthCompound = NSCompoundPredicate(andPredicateWithSubpredicates: [datePredicate, traditionalStrengthTrainingPredicate, functionalStrengthTrainingPredicate]) let selectedWorkoutQuery = HKSampleQuery(sampleType: HKWorkoutType.workoutType(), predicate: strengthCompound, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { strengthQuery, samples, error in guard let samples = samples else { fatalError("An error has occured \(error?.localizedDescription)") } DispatchQueue.main.async { if let workouts = samples as? [HKWorkout] { for workout in workouts { self.muscleStrength.append(workout) } } } } self.healthStore?.execute(selectedWorkoutQuery) } Here is the view I would like to display the count and workouts but nothing is showing struct MuscleView: View { @ObservedObject var healthStoreVM: HealthStoreViewModel var body: some View { List(healthStoreVM.muscleStrength, id: \.self) { workout in Text("\(workout.workoutActivityType.rawValue)") } } }
Posted
by
Post not yet marked as solved
1 Replies
296 Views
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?
Posted
by
Post not yet marked as solved
0 Replies
572 Views
Hello 👋🏼 I would like to create my own Apple Watch app for workouts. I would like to count the number of repetitions of the exercise that I do for example (squat). But my watch is going to sleep. And when the device goes into sleep mode, the counter stops counting, and I wanted to ask. Does the accelerometer run in the background so that it counts the number of squats in the background? What can you recommend ?
Posted
by
Post not yet marked as solved
0 Replies
638 Views
Hi, I´m new at develping in the Apple and SwiftUI environment. My friends and I got an idea to create a simple Fitness app to track down our own exercises and activities. For now we got some concept ideas how the design should be. But for now 4 days I´m watching out for any possible way to create thies small animation. I ´m trying to create this little animation like thy are in the Fitness WatchApp. If you know hou to create those animation: please write it down. Thanks for advance
Posted
by
Post not yet marked as solved
0 Replies
238 Views
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).
Posted
by
Post not yet marked as solved
1 Replies
354 Views
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() } } }
Posted
by
Post not yet marked as solved
1 Replies
415 Views
I am trying to get sleep samples for last 7 days and store them and add whenever I want. I am using HKSampleQuery to fetch all the samples and storing samples which are only inBed samples but sometimes I am getting multiple samples with overlapped time intervals. How to get proper sleep data without any overlaps? I am using below code to get the data func readSleep(from startDate: Date?, to endDate: Date?,Id:Int, Completion: @escaping (Double,Date,Date,Int,String)->Void) { var sleepingHoursCount = 0.0 let healthStore = HKHealthStore() guard let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) else { return } let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictEndDate) let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sortDescriptor]) { (query, result, error) in if error != nil { return } guard let result = result else{ Completion(sleepingHoursCount,startDate!,endDate!,Id,"") return } // do{ if let sleepSamples = result as? [HKCategorySample] { for sample in sleepSamples { guard let sleepValue = HKCategoryValueSleepAnalysis(rawValue: sample.value) else { return } let isInBed = sleepValue == .inBed if(isInBed){ let diffSeconds = sample.endDate.timeIntervalSinceReferenceDate - sample.startDate.timeIntervalSinceReferenceDate sleepingHoursCount += diffSeconds Completion(diffSeconds/3600,sample.startDate,sample.endDate,Id,source) } } } } healthStore.execute(query)
Posted
by
Post not yet marked as solved
2 Replies
771 Views
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
Posted
by
Post not yet marked as solved
0 Replies
305 Views
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
Posted
by
Post not yet marked as solved
0 Replies
254 Views
I want to create an app-less app that uses healthkit information that would be retrieved from the iCloud rather than from the device itself (Getting healthkit data from an app is well described). Is there any possible way to connect to my iCloud with a webhook directly?
Posted
by