Get most recent data point from HKSampleQuery

后端 未结 1 908

I am having trouble getting the latest datapoint for weight using an HKSampleQuery. I have the app permissions set correctly, but HKQuantityTypeIdentifier.bod

1条回答
  •  醉话见心
    2021-01-25 05:54

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

    0 讨论(0)
提交回复
热议问题