Post not yet marked as solved
Hello, im having trouble making my code work and i keep running into the following error, i dont know how to fix my problem:
Cannot convert value of type 'Set<HKQuantityType?>' to expected argument type 'Set<HKObjectType>'
func healthPermission(){
if #available(iOS 15.0, *) {
let healthKitRead : Set<HKObjectType> = [
HKObjectType.quantityType(forIdentifier: .walkingAsymmetryPercentage)!,
HKObjectType.quantityType(forIdentifier: .appleWalkingSteadiness)!,
]
if !HKHealthStore.isHealthDataAvailable() {
print("permission fail")
return
}
healthStore.requestAuthorization(toShare: [], read: healthKitRead)
{ (success, error) -> Void in
print("Permission sucess")
}
} else {
// Fallback on earlier versions
}
}
Thanks for any help or advice.
Post not yet marked as solved
I have a non-native react app, which uses healthkit with an ionic plugin.
I want to prompt the user to change the settings if he wants to enter more data after the initial authorization step.
is there a way to do so?
Post not yet marked as solved
I can able to get my health data list from health kit. I used below code to get my today's step count :
`func getTodaysSteps(completion: @escaping (Double) -> Void) {
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let now = Date()
let startOfDay = Calendar.current.startOfDay(for: now)
let predicate = HKQuery.predicateForSamples(
withStart: startOfDay,
end: now,
options: .strictStartDate
)
let query = HKStatisticsQuery(
quantityType: stepsQuantityType,
quantitySamplePredicate: predicate,
options: .cumulativeSum
) { _, result, _ in
guard let result = result, let sum = result.sumQuantity() else {
completion(0.0)
return
}
completion(sum.doubleValue(for: HKUnit.count()))
}
healthStore.execute(query)
}`
But i have one more health data of my brother, where he invited me to see his health data in my real device. Now i was not able to read / get his health data. Is there any way to get that.
Any solution would be great ...!
Post not yet marked as solved
What are the various scenarios when Apple records HRV(Heart Rate Variability) automatically in the background ?
Apple definitely computes HRV when someone uses Breathe App (in Mindfulness) on their Apple Watch and when we closely look at the details of data collected in HealthKit app, it depicts Algorithm Version as 2 But Apple also records HRV in some other scenarios which depicts Algorithm Version as 1. What are those scenarios?
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
https://developer.apple.com/documentation/healthkit/hkhealthstore/1614175-enablebackgrounddelivery, as Apple official described the technical documentation, We can read the health data in HealthStore when the application is not started or in the Kill state, when the data in the health App is updated. But it doesn't work for me, I don't know why, I hope I can get the answer here, thank you very much!
Here is my code:
typealias AccessRequestCallback = (_ success: Bool, _ error: Error?) -> Void
/// Helper for reading and writing to HealthKit.
class HealthKitManager: NSObject {
static let shared = HealthKitManager()
private override init() {}
private let healthStore = HKHealthStore()
/// Requests access to all the data types the app wishes to read/write from HealthKit.
/// On success, data is queried immediately and observer queries are set up for background
/// delivery. This is safe to call repeatedly and should be called at least once per launch.
func requestAccessWithCompletion(completion: @escaping AccessRequestCallback) {
guard HKHealthStore.isHealthDataAvailable() else {
debugPrint("Can't request access to HealthKit when it's not supported on the device.")
return
}
let writeDataTypes = dataTypesToWrite()
let readDataTypes = dataTypesToRead()
healthStore.requestAuthorization(toShare: writeDataTypes, read: readDataTypes) { [weak self] success, error in
guard let strongSelf = self else { return }
if success {
debugPrint("Access to HealthKit data has been granted")
strongSelf.readHealthKitData()
strongSelf.setUpBackgroundDeliveryForDataTypes(types: readDataTypes)
} else {
debugPrint("Error requesting HealthKit authorization: \(error?.localizedDescription ?? "")")
}
DispatchQueue.main.async {
completion(success,error)
}
}
}
}
// MARK: - Private
private extension HealthKitManager {
/// Initiates an `HKAnchoredObjectQuery` for each type of data that the app reads and stores
/// the result as well as the new anchor.
func readHealthKitData() {
debugPrint("===============readHealthKitData================")
// HealthKitManager.shared.addLocalPush(title: "readHealthKitData")
}
/// Sets up the observer queries for background health data delivery.
///
/// - parameter types: Set of `HKObjectType` to observe changes to.
private func setUpBackgroundDeliveryForDataTypes(types: Set<HKObjectType>) {
for type in types {
guard let sampleType = type as? HKSampleType else {
debugPrint("ERROR: \(type) is not an HKSampleType");
continue
}
var query: HKQuery!
query = HKObserverQuery(sampleType: sampleType, predicate: nil) { [weak self] query, completionHandler, error in
if error != nil {
debugPrint("observer query update handler called for type \(type), error: \(error?.localizedDescription ?? "")")
return
}
guard let strongSelf = self else { return }
strongSelf.queryForUpdates(type: type)
completionHandler()
}
healthStore.execute(query)
healthStore.enableBackgroundDelivery(for: type, frequency: .immediate) { success, error in
if error != nil {
debugPrint("enableBackgroundDeliveryForType handler called for \(type) - success: \(success), error: \(error?.localizedDescription ?? "")")
return
}
debugPrint("enableBackgroundDeliveryForType: \(type)")
}
}
}
/// Initiates HK queries for new data based on the given type
///
/// - parameter type: `HKObjectType` which has new data avilable.
private func queryForUpdates(type: HKObjectType) {
// self.addLocalPush(title: "queryForUpdates")
switch type {
case HKObjectType.quantityType(forIdentifier: .bodyMass):
debugPrint("HKQuantityTypeIdentifier-BodyMass")
case HKObjectType.quantityType(forIdentifier: .height):
debugPrint("HKQuantityTypeIdentifier-Height")
case HKObjectType.quantityType(forIdentifier: .stepCount):
debugPrint("HKQuantityTypeIdentifier-StepCount")
case is HKWorkoutType:
debugPrint("HKWorkoutType")
default: debugPrint("Unhandled HKObjectType: \(type)")
}
}
/// Types of data that this app wishes to read from HealthKit.
///
/// - returns: A set of HKObjectType.
private func dataTypesToRead() -> Set<HKObjectType> {
if #available(iOS 14.0, *) {
return Set(arrayLiteral:
HKObjectType.quantityType(forIdentifier: .bodyMass)!,
HKObjectType.quantityType(forIdentifier: .height)!,
HKObjectType.categoryType(forIdentifier: .handwashingEvent)!,
HKObjectType.quantityType(forIdentifier: .stepCount)!,
HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
HKObjectType.workoutType())
} else {
return Set(arrayLiteral:
HKObjectType.quantityType(forIdentifier: .bodyMass)!,
HKObjectType.quantityType(forIdentifier: .height)!,
HKObjectType.quantityType(forIdentifier: .stepCount)!,
HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
HKObjectType.workoutType())
}
}
/// Types of data that this app wishes to write to HealthKit.
///
/// - returns: A set of HKSampleType.
private func dataTypesToWrite() -> Set<HKSampleType> {
if #available(iOS 14.0, *) {
return Set(arrayLiteral:
HKObjectType.quantityType(forIdentifier: .bodyMass)!,
HKObjectType.quantityType(forIdentifier: .height)!,
HKObjectType.categoryType(forIdentifier: .handwashingEvent)!,
HKObjectType.quantityType(forIdentifier: .stepCount)!,
HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
HKObjectType.workoutType())
} else {
return Set(arrayLiteral:
HKObjectType.quantityType(forIdentifier: .bodyMass)!,
HKObjectType.quantityType(forIdentifier: .height)!,
HKObjectType.quantityType(forIdentifier: .stepCount)!,
HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
HKObjectType.workoutType())
}
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let vc: ViewController = .init()
window?.rootViewController = vc
window?.makeKeyAndVisible()
healthKitManager.requestAccessWithCompletion() { success, error in
if success { print("HealthKit access granted") }
else { print("Error requesting access to HealthKit: \(error?.localizedDescription ?? "")") }
}
return true
}
Post not yet marked as solved
Hello, I am a meditator and am frustrated with the categorization that Apple provides in Health. It seems to me that there ought to be a category for meditation by itself, maybe with Tai Chi or other meditative activity. Putting it under Workouts misses the point. Thanks Eric
I am currently working on an app that compiles sensor data to a csv file for use in health applications. This data is collected in the background via HKWorkoutSession. I'm not using any data from the healthstore, however, it is needed to start the workout session. During background run time, the apple watch continuously runs the heartrate monitor (the green light on the back of the watch).
Is there any way to disable this light from turning on? This app must maintain a low battery usage profile so it may run continuously for 12+ hours, however, the heart rate sensor chews through battery life.
Post not yet marked as solved
Do I have to pay when I use healthKit in my app?
Would you tell me how does it cost or provide related documents?
I want to know really detailed information cause the app has many users
Post not yet marked as solved
I use the Fit! App on my iPhone for my workouts and all of a sudden it’s saying the token has expired. What can I do to fix it?
Post not yet marked as solved
I want to do an app for an apple watch using Heart rate and Electrodermal Activity from Healthkit, but i don't find the frecuency of the data, i mean how many times per second the library send me data?
Post not yet marked as solved
While testing on device (Apple Watch) attempting to save an HKWorkout into HealthKit I am adding samples of distance samples, calories, heart rates and vo2Max to the workout. Unfortunately unlike this question I am not getting as detailed as a trace back...as far as I can tell it's crashing on adding a sample but I can't tell which sample it is or why?Code:private func addSamples(toWorkout workout: HKWorkout, from startDate: Date, to endDate: Date, handler: @escaping (Bool, Error?) -> Void) {
let vo2MaxSample = HKQuantitySample(type: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.vo2Max)!, quantity: vo2MaxQuantity(), start: startDate, end: endDate)
var samples = [HKQuantitySample]()
for distanceWalkingRunningSample in distanceWalkingRunningSamples {
samples.append(distanceWalkingRunningSample)
}
for energySample in energySamples {
samples.append(energySample)
}
samples.append(vo2MaxSample)
samples.append(contentsOf: heartRateValues)
// Add samples to workout
healthStore.add(samples, to: workout) { (success: Bool, error: Error?) in
if error != nil {
print("Adding workout subsamples failed with error: \(String(describing: error))")
handler(false, error)
}
if success {
print("Success, samples have been added, workout Saved.") //WorkoutStartDate = \(workout.startDate) WorkoutEndDate = \(workout.endDate)
handler(true, nil)
} else {
print("Adding workout subsamples failed no error reported")
handler(false, nil)
}
}
}Trace:Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Triggered by Thread: 0 Application Specific Information: abort() called Filtered syslog: None found Last Exception Backtrace: 0 CoreFoundation 0x1bdf75e8 __exceptionPreprocess + 124 1 libobjc.A.dylib 0x1b15717c objc_exception_throw + 33 2 CoreFoundation 0x1bdf752c +[NSException raise:format:] + 103 3 HealthKit 0x273dbdde -[HKObject _validateForCreation] + 111 4 HealthKit 0x273dbc48 +[HKObject _newDataObjectWithMetadata:device:config:] + 219 5 HealthKit 0x273dbb30 +[HKSample _newSampleWithType:startDate:endDate:device:metadata:config:] + 159 6 HealthKit 0x273e9ba8 +[HKWorkout _workoutWithActivityType:startDate:endDate:workoutEvents:duration:totalActiveEnergyBurned:totalBasalEnergyBurned:totalDistance:totalSwimmingStrokeCount:totalFlightsClimbed:goalType:goal:device:metadata:config:] + 431 7 HealthKit 0x274a9342 +[HKWorkout workoutWithActivityType:startDate:endDate:workoutEvents:totalEnergyBurned:totalDistance:device:metadata:] + 109 8 HealthKit 0x274a9160 +[HKWorkout workoutWithActivityType:startDate:endDate:workoutEvents:totalEnergyBurned:totalDistance:metadata:] + 87Thread 0 name: Dispatch queue: com.apple.main-threadThread 0 Crashed:0 libsystem_kernel.dylib 0x1b9e443c __pthread_kill + 81 libsystem_pthread.dylib 0x1baec270 pthread_kill$VARIANT$mp + 3342 libsystem_c.dylib 0x1b96d28e abort + 1063 libc++abi.dylib 0x1b136cfe __cxa_bad_cast + 04 libc++abi.dylib 0x1b136e8a default_unexpected_handler+ 16010 () + 05 libobjc.A.dylib 0x1b1573e0 _objc_terminate+ 29664 () + 1026 libc++abi.dylib 0x1b1493fc std::__terminate(void (*)+ 91132 ()) + 67 libc++abi.dylib 0x1b148ed6 __cxxabiv1::exception_cleanup_func+ 89814 (_Unwind_Reason_Code, _Unwind_Exception*) + 08 libobjc.A.dylib 0x1b157274 _objc_exception_destructor+ 29300 (void*) + 09 CoreFoundation 0x1bdf7530 -[NSException initWithCoder:] + 010 HealthKit 0x273dbde2 -[HKObject _validateForCreation] + 11611 HealthKit 0x273dbc4c +[HKObject _newDataObjectWithMetadata:device:config:] + 22412 HealthKit 0x273dbb34 +[HKSample _newSampleWithType:startDate:endDate:device:metadata:config:] + 16413 HealthKit 0x273e9bac +[HKWorkout _workoutWithActivityType:startDate:endDate:workoutEvents:duration:totalActiveEnergyBurned:totalBasalEnergyBurned:totalDistance:totalSwimmingStrokeCount:totalFlightsClimbed:goalType:goal:device:metadata:config:] + 43614 HealthKit 0x274a9346 +[HKWorkout workoutWithActivityType:startDate:endDate:workoutEvents:totalEnergyBurned:totalDistance:device:metadata:] + 11415 HealthKit 0x274a9164 +[HKWorkout workoutWithActivityType:startDate:endDate:workoutEvents:totalEnergyBurned:totalDistance:metadata:] + 92
Post not yet marked as solved
the specifics are pretty straight forward we just need to the code to get HRV in realtime and pasively like the zendo app in the app store
https://github.com/zendotools/zendo but that github doesnt compile. on the watch i can get the Heart rate to update but not hear rate variability. I need it in real time while the user is looking at his watch and passively throught out the day,.
Post not yet marked as solved
I'm trying to request access to read/write from HealthKit but am un able to figure out how to solve this error. When I attempt to put in "NSHealthUpdateUsageDescription" to my Info.plist file I get the Privacy - "Update Usage Description" equivalent, but still get this error.
I'm working with some code based on WWDC20 10664.
Using HKHeartbeatSeriesQuery, I am able to get beat-to-beat timestamps. How to get the BPM for those timestamps?I am able to see the BPM in apple health app.
Post not yet marked as solved
Hello,Extremely excited with the new health and SOS features being built into the Apple ecosystem. Keep up the great work Apple 🙂In order to extend the capabilities of these services, I'm interested in:Importing / Exporting emergency contacts from HealthkitExecute SOS signal from 3rd party applicationI took a dive into the Healthkit documentation and searched the forums, however, have not found anything pertaining to my use cases. Any help on this is greatly appreciated! HealthKit Data Types:https://developer.apple.com/documentation/healthkit/health_data_types?changes=_6
Post not yet marked as solved
I've successfully queried lots of HealthKit data, but I'm having trouble querying "appleStandHour" over some time range such as the last week. I'm sure the issue is that this data is a "category" instead of a "statistic". Can someone show me or give me a link that shows how to do this query?
Post not yet marked as solved
Hello!
Today I worked for the first time with Apple Health Kit and successfully saved a workout in Health with the basic informations (activityType, start and end).
My app is in basic function an interval timer where you can create your own workout. Now in the next step I want to add the calories burned in the workout. This information is stored in the attribute 'totalEnergyBurned'.
Do I need to calculate this value myself or can I query this value directly if the user is wearing an Apple Watch? Or maybe the value is even automatically added to the workout if there is the corresponding record? (So far I have only tested the app in the simulator, which is why I can't answer this possibility).
My current code:
func saveToHealthKit(entryID: String){
if HKHealthStore.isHealthDataAvailable() {
let healthStore = HKHealthStore()
if(healthStore.authorizationStatus(for: HKObjectType.workoutType()) == .sharingAuthorized && healthStore.authorizationStatus(for: HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)!) == .sharingAuthorized){
let newWorkout = HKWorkout(activityType: HKWorkoutActivityType.highIntensityIntervalTraining, start: entry.date!, end: Date())
healthStore.save(newWorkout) { success, error in
guard success else {
// Perform proper error handling here.
return
}
// Add detail samples here.
}
}
}
}
}
Thanks :)
Post not yet marked as solved
So in iOS15.4 the HealthKit authorization sheet which gives you permissions to select HealthKit options comes up in Portrait Only, and my App is in Landscape. Wondering if there is a way to tell the authorization sheet to display in Landscape?
Additionally in iOS15.4 this authorization sheet displays a high NavBar in Portrait by default instead of the compact NavBar, thus after the user accepts the HealthKit permissions and the authorization sheet is dismissed, the App switches back to Landscape, but is now stuck with the high NavBar instead of the compact NavBar, and there appears to be no way to switch it back to the compact NavBar after this. Calling the NavBar itself and programmatically setting compact doesn't work. So the only way to get the compact NavBar back is to restart the App. So my second question is there a way to get the HealthKit authorization sheet to come up with a compact NavBar instead of the high NavBar?
Post not yet marked as solved
I have a problem with Apple HealthKit authorization. Everything worked fine until update of Xcode to version 13.3. It seems that that request for authorization is not fired, even when I explicitly declared that I want to request authorization onAppear of ContentView. This is code for ContentView:
import SwiftUI
struct ContentView: View {
@EnvironmentObject var firebaseManager: FirebaseManager
@EnvironmentObject var healthkitManager: HealthKitManager
var body: some View {
NavigationView {
if firebaseManager.signedIn {
HomePageView()
} else {
SignInView()
}
}
.onAppear {
healthkitManager.authorizeHealthKit()
firebaseManager.signedIn = firebaseManager.isSignedIn }
}
}
Function in HealthKitManager looks like this:
func authorizeHealthKit() {
//Check to see if HealthKit Is Available on this device
guard HKHealthStore.isHealthDataAvailable() else {
print("HealthKit data not available on this device")
return
}
// Set types to read and write in HealthStore
let typesToRead: Set = [
HKObjectType.characteristicType(forIdentifier: .dateOfBirth)!,
HKObjectType.quantityType(forIdentifier: .bloodGlucose)!,
HKObjectType.quantityType(forIdentifier: .insulinDelivery)!,
HKObjectType.quantityType(forIdentifier: .dietaryCarbohydrates)!,
HKObjectType.quantityType(forIdentifier: .stepCount)!,
HKObjectType.quantityType(forIdentifier: .heartRate)!,
HKObjectType.quantityType(forIdentifier: .appleExerciseTime)!,
]
let typesToWrite: Set = [
HKObjectType.quantityType(forIdentifier: .bloodGlucose)!,
HKObjectType.quantityType(forIdentifier: .insulinDelivery)!,
HKObjectType.quantityType(forIdentifier: .dietaryCarbohydrates)!,
]
// Request authorization for those quantity types.
healthStore.requestAuthorization(toShare: typesToWrite, read: typesToRead) { (success, error) in }
}
I've tried to add key Privacy - Health Update Usage Description and Privacy - Health Share Usage Description with some string values to Info tab in project file, but still nothing. When I build application, I get this in console:
[auth] FAILED prompting authorization request to share (
HKQuantityTypeIdentifierBloodGlucose,
HKQuantityTypeIdentifierDietaryCarbohydrates,
HKQuantityTypeIdentifierInsulinDelivery
), read (
HKCharacteristicTypeIdentifierDateOfBirth,
HKQuantityTypeIdentifierHeartRate,
HKQuantityTypeIdentifierBloodGlucose,
HKQuantityTypeIdentifierInsulinDelivery,
HKQuantityTypeIdentifierDietaryCarbohydrates,
HKQuantityTypeIdentifierAppleExerciseTime,
HKQuantityTypeIdentifierStepCount
)
I read some articles, tried multiple possible solutions, restarted my Mac, but everything without success. Should there be a problem because I have two environment object? I'll be thankful for any ideas...