如何渐进式使用健康包示例查询

how to use health kit sample query in progressive ways

我真的想要执行 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.

我认为代码 运行 没有进步。 HKSampleQuery 运行 的 resultHandler 什么时候开始?在使用查询结果之前,我真的希望处理程序代码 运行。

resultsHandler 运行时记录在 HKSampleQuery reference:

After instantiating the query, call the HKHealthStore class’s executeQuery: method to run this query. Queries run on an anonymous background queue. As soon as the query is complete, the results handler is executed on the background queue. You typically dispatch these results to the main queue to update the user interface.

由于查询是异步执行的,您应该执行取决于查询结果的工作以响应调用 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 相关的工作以避免同步问题。