I am trying to get and update height from Healthkit but not getting any document for swift 3.
Is there any way to get height from healthKit also to update height in healthKit?
I am trying to get and update height from Healthkit but not getting any document for swift 3.
Is there any way to get height from healthKit also to update height in healthKit?
Create an healthkit instance
let healthKitStore:HKHealthStore = HKHealthStore()
Request Permission
func requestPermissions(completion: @escaping ((_ success:Bool, _ error:Error?) -> Void)){
let healthKitTypesToRead : Set<HKSampleType> = [
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!,
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!,
]
let healthKitTypesToWrite: Set<HKSampleType> = [
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!,
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!,
]
if !HKHealthStore.isHealthDataAvailable() {
print("Error: HealthKit is not available in this Device")
completion(false, error)
return
}
healthKitStore.requestAuthorization(toShare: healthKitTypesToWrite, read: healthKitTypesToRead) { (success, error) -> Void in
completion(success,error )
}
}
Reading Height
let heightType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!
let query = HKSampleQuery(sampleType: heightType, predicate: nil, limit: 1, sortDescriptors: nil) { (query, results, error) in
if let result = results?.first as? HKQuantitySample{
print("Height => \(result.quantity)")
}else{
print("OOPS didnt get height \nResults => \(results), error => \(error)")
}
}
self.healthKitStore.execute(query)
Writing Height
let height = YOUR_HEIGHT
if let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height) {
let date = Date()
let quantity = HKQuantity(unit: HKUnit.inch(), doubleValue: height!)
let sample = HKQuantitySample(type: type, quantity: quantity, start: date, end: date)
self.healthKitStore.save(sample, withCompletion: { (success, error) in
print("Saved \(success), error \(error)")
})
}
Now if you want to read and write Weight then just use
HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)
Note: Don't forget to add these permissions
Privacy - Health Update Usage Description
Privacy - Health Share Usage Description
Hope this is helpful to others who are still searching for it
© 2022 - 2024 — McMap. All rights reserved.