从HKSampleQuery获取最新数据点 [英] Get most recent data point from HKSampleQuery

查看:214
本文介绍了从HKSampleQuery获取最新数据点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用 HKSampleQuery 获取最新的重量数据点。我已正确设置应用权限,但 HKQuantityTypeIdentifier.bodyMass 未返回Health应用中的最新数据条目。

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.

我应该如何使用 HKSampleQuery 获取体重的最新数据点?

How am I supposed to grab the latest datapoint for body mass using an HKSampleQuery?

我认为这是因为我为重量设定的0.0是我要回来的东西没有控制台输出readWeight

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

我的代码包括调试过程如下。

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)
}

该函数使用如下:

var Weight = 0.0 //The probable reason that it returns 0.0
readWeight() { weight in
    Weight = weight
}






编辑2



权限代码:


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
        }


推荐答案

HealthKit文档(我强烈建议您完整阅读), HKSampleQuery 使不保证它返回的样品或它返回的顺序除非指定样品的返回方式。

As explained in the HealthKit documentation (which I strongly urge you to read in its entirety), an HKSampleQuery makes no guarantees about the samples it returns or the order in which it returns them unless you specify how the samples should be returned.

对于您的情况,可以通过多种方式返回最新的数据点。看一下 HKSampleQuery 和以下方法:

For your case, returning the most recent data point can be done in a number of ways. Take a look at HKSampleQuery and the following method:

init(sampleType:predicate:limit:sortDescriptors:resultsHandler:)




你可以提供一个返回样本的排序顺序,或限制返回的样本数。

You can provide a sort order for the returned samples, or limit the number of samples returned.

- HKSampleQuery文档

-- HKSampleQuery Documentation

在您的代码中,您已适当限制查询,以便它只返回一个样本。这是正确的,避免了用例中不必要的开销。但是,您的代码为 sortDescriptors 参数指定 nil 。这意味着查询可以以任何顺序返回样本(因此,返回给您的单个样本通常不是您想要的)。

In your code, you have appropriately limited the query so that it only returns one sample. This is correct and avoids unnecessary overhead in your use case. However, your code specifies nil for the sortDescriptors parameter. This means that the query can return samples in whatever order it pleases (thus, the single sample being returned to you is usually not what you're looking for).


一组排序描述符,用于指定此查询返回的结果的顺序。如果您不需要特定顺序的结果,则传递nil。

An array of sort descriptors that specify the order of the results returned by this query. Pass nil if you don’t need the results in a specific order.

注意

HealthKit定义了一些排序标识符(例如,
HKSampleSortIdentifierStartDate HKWorkoutSortIdentifierDuration )。仅在查询中使用您使用这些标识符创建的排序描述符。您不能使用它们来执行内存排序的样本数组。

Note
HealthKit defines a number of sort identifiers (for example, HKSampleSortIdentifierStartDateand HKWorkoutSortIdentifierDuration). Use the sort descriptors you create with these identifiers only in queries. You cannot use them to perform an in-memory sort of an array of samples.

- HKSampleQuery.init(...)文档

-- HKSampleQuery.init(...) Documentation

那么,解决方案就是简单地提供一个排序描述符,要求 HKSampleQuery 按日期降序排序样本(意思是最近的一个将在列表中排在第一位。)

So, the solution then, is to simply provide a sort descriptor that asks the HKSampleQuery to order samples by date in descending order (meaning the most recent one will be first in a list).

我希望上面的答案比简单的副本更有帮助/粘贴您需要解决问题的代码。即便如此,为此特定用例提供正确样本的代码如下:

I hope that the answer above is more helpful than a simple copy/paste of the code you need to fix the issue. Even so, the code to provide the correct sample for this specific use case is below:

// 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...
}

这篇关于从HKSampleQuery获取最新数据点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆