如何逐步使用健康包样本查询



我真的想要执行HKSampleQuery的结果。但是,我总是不能在执行查询后得到正确的结果。

我的情况如下(错误处理代码被删除):

let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
// get the latest step count sample
let stepSampleQuery: HKSampleQuery = HKSampleQuery(sampleType: (stepCountQty)!,
    predicate: nil,
    limit: 1,
    sortDescriptors: [sortDescriptor]) {
        (query, results, error) -> Void in
        if let result = results as? [HKQuantitySample] {
            // result[0] is the sample what I want
            self.lastStepDate = result[0].startDate
            print("readLastStep: ", self.lastStepDate)
        }
}
self.healthStore.executeQuery(query)
// now, I want to use the "self.lastStepDate"
// But, I cannot get the appropriate value of the variable.

我不认为代码是逐步运行的。HKSampleQueryresultHandler什么时候运行?我真的希望在使用查询结果之前运行处理程序代码。

resultsHandler运行时记录在HKSampleQuery参考中:

实例化查询后,调用HKHealthStore类的executeQuery:执行此查询的方法。查询在匿名对象上运行背景队列。查询完成后,结果处理程序在后台队列上执行。你通常会调度这些结果到主队列更新用户界面。

由于查询是异步执行的,因此您应该执行依赖于响应resultsHandler调用的查询结果的工作。例如,您可以这样做:

// get the latest step count sample
let stepSampleQuery: HKSampleQuery = HKSampleQuery(sampleType: (stepCountQty)!,
    predicate: nil,
    limit: 1,
    sortDescriptors: [sortDescriptor]) {
        (query, results, error) -> Void in
        if let result = results as? [HKQuantitySample] {
            // result[0] is the sample what I want
            dispatch_async(dispatch_get_main_queue()) {
               self.lastStepDate = result[0].startDate
               print("readLastStep: ", self.lastStepDate)
               self.doSomethingWithLastStepDate()
            }
        }
}
self.healthStore.executeQuery(query)

请注意,由于处理程序是在后台队列上调用的,因此我已经在主队列上完成了与lastStepDate相关的工作,以避免同步问题。

最新更新