I am having trouble getting the latest datapoint for weight using an HKSampleQuery
. I have the app permissions set correctly, but HKQuantityTypeIdentifier.bodyMass
is not returning the most recent data entry from the Health app.
How am I supposed to grab the latest datapoint for body mass using an HKSampleQuery
?
The reason I think this is because the 0.0 I set for Weight
is what is returning and I am getting no console output on readWeight
Edit 1
My code including the debugging process is as follows.
public func readWeight(result: @escaping (Double) -> Void) {
if (debug){print("Weight")}
let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)
let weightQuery = HKSampleQuery(sampleType: quantityType!, predicate: nil, limit: 1, sortDescriptors: nil) {
query, results, error in
if (error != nil) {
if (self.debug){print(error!)}
result(166.2) //Set as average weight for American
return
}
guard let results = results else {
if (self.debug){print("No results of query")}
result(166.2)
return
}
if (results.count == 0) {
if (self.debug){print("Zero samples")}
result(166.2)
return
}
guard let bodymass = results.first as? HKQuantitySample else {
if (self.debug){print("Type problem with weight")}
result(166.2)
return
}
if (self.debug){print("Weight" + String(bodymass.quantity.doubleValue(for: HKUnit.pound())))}
if (bodymass.quantity.doubleValue(for: HKUnit.pound()) != 0.0) {
result(bodymass.quantity.doubleValue(for: HKUnit.pound()))
} else {
result(166.2)
}
}
healthKitStore.execute(weightQuery)
}
The function is used like this:
var Weight = 0.0 //The probable reason that it returns 0.0
readWeight() { weight in
Weight = weight
}
Edit 2
Permission Code:
let healthKitTypesToRead : Set<HKQuantityType> = [
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryWater)!,
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!,
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.appleExerciseTime)!
]
let healthKitTypesToWrite: Set<HKQuantityType> = [
HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryWater)!
]
if (!HKHealthStore.isHealthDataAvailable()) {
if (self.debug){print("Error: HealthKit is not available in this Device")}
return
}
healthKitStore.requestAuthorization(toShare: healthKitTypesToWrite, read: healthKitTypesToRead) { (success, error) -> Void in
if (success) {
DispatchQueue.main.async() {
self.pointView.text = String(self.currentPoints())
}
}
if ((error) != nil) {
if (self.debug){print(error!)}
return
}