Hey, guys. I try to get user's weight by using HealthKit in SwiftUI. can anyone give a example to show me how to do it?
debugPrint("sync begin...")
if HKHealthStore.isHealthDataAvailable() {
let healthStore = HKHealthStore()
let allTypes = Set([HKCharacteristicType(.biologicalSex),
HKCharacteristicType(.dateOfBirth),
HKQuantityType(.bodyFatPercentage),
HKQuantityType(.height),
HKQuantityType(.bodyMass)])
healthStore.requestAuthorization(toShare: [], read: allTypes) { (success, error) in
if success {
debugPrint("HealthKit authorized succeed.")
self.isAvailable = true
self.healthStore = healthStore
do{
if self.isAvailable {
debugPrint("healstore is available...")
let bioSex = try self.healthStore?.biologicalSex()
debugPrint("\(bioSex)")
let birth = try self.healthStore?.dateOfBirthComponents()
debugPrint(birth?.date)
var sampleType: HKSampleType = HKQuantityType(.height)
let heightQuery = HKSampleQuery(sampleType: sampleType, predicate: nil, limit: 10, sortDescriptors: nil, resultsHandler: {(query, result, error)in
debugPrint("handling results...")
if let samples = result {
for sample in samples {
let quantitySample = sample as! HKQuantitySample
let height = quantitySample.quantity.doubleValue(for: .meterUnit(with:.centi))
debugPrint("\(height)")
}
}
})
self.healthStore?.execute(heightQuery)
}
}catch(let error){
debugPrint(error)
}
}
}
}