Get most recent data point from HKSampleQuery

吃可爱长大的小学妹 提交于 2019-12-02 04:02:40

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.

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 Documentation

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

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.

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(...) Documentation

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...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!