首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从HKSampleQuery获取最新数据点

从HKSampleQuery获取最新数据点
EN

Stack Overflow用户
提问于 2017-06-30 15:14:01
回答 1查看 2.2K关注 0票数 1

我在使用HKSampleQuery获取最新的权重数据时遇到了困难。我已经正确设置了应用程序权限,但是HKQuantityTypeIdentifier.bodyMass没有从Health返回最新的数据输入。

如何使用HKSampleQuery**?**获取最新的体重数据?

我认为这是因为我为Weight设置的0.0是返回的,在readWeight上没有控制台输出

编辑1

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

代码语言:javascript
复制
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)
}

该函数的用法如下:

代码语言:javascript
复制
var Weight = 0.0 //The probable reason that it returns 0.0
readWeight() { weight in
    Weight = weight
}

编辑2

“许可法”:

代码语言:javascript
复制
    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
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-07 16:35:44

正如在HealthKit文档中所解释的(我强烈敦促您阅读它的全部内容),HKSampleQuery不能保证它返回的样本或返回它们的顺序,除非您指定应该如何返回这些样本。

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

代码语言:javascript
复制
init(sampleType:predicate:limit:sortDescriptors:resultsHandler:)

您可以为返回的样本提供排序顺序,也可以限制返回的样本数。 -- https://developer.apple.com/documentation/healthkit/hksamplequery

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

指定此查询返回的结果顺序的排序描述符数组。如果您不需要按特定顺序处理结果,则传递零。 Note HealthKit定义了许多排序标识符(例如,HKSampleSortIdentifierStartDateHKWorkoutSortIdentifierDuration)。仅在查询中使用使用这些标识符创建的排序描述符。您不能使用它们来执行内存中的示例数组。 -- https://developer.apple.com/documentation/healthkit/hksamplequery/1615055-init

因此,解决方案就是简单地提供一个排序描述符,它要求HKSampleQuery按日期降序(这意味着最近的样本将位于列表的第一位)。

我希望上面的答案比修复问题所需的代码的简单复制/粘贴更有帮助。尽管如此,为提供正确示例的代码(这个特定的用例)如下所示:

代码语言:javascript
复制
// 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...
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44849723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档