aro*_*ugh 1 ios swift healthkit hksamplequery
我无法使用HKSampleQuery. 我已正确设置应用程序权限,但未HKQuantityTypeIdentifier.bodyMass从 Health 应用程序返回最新的数据条目。
我应该如何使用 获取最新的体重数据点HKSampleQuery?
我认为这是因为我设置的 0.0Weight是返回的值,并且我没有得到任何控制台输出readWeight
我的代码包括调试过程如下。
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)
}
Run Code Online (Sandbox Code Playgroud)
该函数是这样使用的:
var Weight = 0.0 //The probable reason that it returns 0.0
readWeight() { weight in
Weight = weight
}
Run Code Online (Sandbox Code Playgroud)
权限代码:
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
}
Run Code Online (Sandbox Code Playgroud)
正如HealthKit 文档中所解释的(我强烈建议您完整阅读),除非您指定应如何返回样本,否则anHKSampleQuery不保证它返回的样本或返回它们的顺序。
对于您的情况,可以通过多种方式返回最新的数据点。看看HKSampleQuery下面的方法:
init(sampleType:predicate:limit:sortDescriptors:resultsHandler:)
Run Code Online (Sandbox Code Playgroud)
您可以为返回的样本提供排序顺序,或限制返回的样本数量。
在您的代码中,您对查询进行了适当的限制,使其仅返回一个样本。这是正确的,并避免了您的用例中不必要的开销。但是,您的代码指定nil了sortDescriptors参数。这意味着查询可以按照它喜欢的任何顺序返回样本(因此,返回给您的单个样本通常不是您要查找的)。
一个排序描述符数组,用于指定此查询返回的结果的顺序。如果您不需要特定顺序的结果,则传递 nil。
注意
HealthKit 定义了许多排序标识符(例如,HKSampleSortIdentifierStartDate和HKWorkoutSortIdentifierDuration)。仅在查询中使用您使用这些标识符创建的排序描述符。您不能使用它们来执行样本数组的内存中排序。
因此,解决方案是简单地提供一个排序描述符,要求HKSampleQuery按日期降序对样本进行排序(意味着最新的将在列表中排在第一位)。
我希望上面的答案比解决问题所需的代码的简单复制/粘贴更有帮助。即便如此,为这个特定用例提供正确示例的代码如下:
// Create an NSSortDescriptor
let sort = [
// We want descending order to get the most recent date FIRST
NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
]
let weightQuery = HKSampleQuery(sampleType: quantityType!, predicate: nil, limit: 1, sortDescriptors: sort) {
// Handle errors and returned samples...
}
Run Code Online (Sandbox Code Playgroud)