我无法使用HKSampleQuery
. 我正确设置了应用程序权限,但HKQuantityTypeIdentifier.bodyMass
没有从 Health 应用程序返回最新的数据条目。
我应该如何使用 获取最新的体重数据点HKSampleQuery
?
我认为这是因为我设置的 0.0Weight
是返回的内容,我没有得到控制台输出readWeight
编辑 1
我的代码包括调试过程如下。
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)
}
该函数的使用如下:
var Weight = 0.0 //The probable reason that it returns 0.0
readWeight() { weight in
Weight = weight
}
编辑 2
权限代码:
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
}