A general-purpose query that returns a snapshot of all the matching samples currently saved in the HealthKit store.


@interface HKSampleQuery : HKQuery


You can use sample queries to search for any concrete subclasses of the HKSample class, including HKCategorySample, HKCorrelation, HKQuantitySample, and HKWorkout objects.

The sample query returns sample objects that match the provided type and predicate. You can provide a sort order for the returned samples, or limit the number of samples returned. Other query classes can be used to perform more specialized searches and calculations. For more information, see HKQuery.

Sample queries are immutable: The query’s properties are set when the query is first created. They cannot change.

Executing Queries

You create a sample query by calling the initWithSampleType:predicate:limit:sortDescriptors:resultsHandler: initializer. After the query is instantiated, you run it by calling the HealthKit store’s executeQuery: method. This method runs the query on an anonymous background queue. When the query is complete, it executes the results handler on the background queue. Typically, you dispatch these results back to the main queue to update your user interface.

Listing 1 shows how to build a query and process the results. This code is taken from the AAPLJournalViewController.m file in the sample code project Fit: Store and Retrieve HealthKit Data.

Listing 1

Writing HealthKit data

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
NSDate *startDate = [calendar dateFromComponents:components];
NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryEnergyConsumed];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:nil resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
    if (!results) {
        NSLog(@"An error occured fetching the user's tracked food. In your app, try to handle this gracefully. The error was: %@.", error);
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.foodItems removeAllObjects];
        for (HKQuantitySample *sample in results) {
            NSString *foodName = sample.metadata[HKMetadataKeyFoodType];
            double joules = [sample.quantity doubleValueForUnit:[HKUnit jouleUnit]];
            AAPLFoodItem *foodItem = [AAPLFoodItem foodItemWithName:foodName joules:joules];
            [self.foodItems addObject:foodItem];
        [self.tableView reloadData];
[self.healthStore executeQuery:query];

The above sample code starts by calculating the start and end dates for the desired time interval, to produce a 24-hour period, starting at the previous midnight. Next, it defines a sample type for dietary energy consumed, and a predicate that filters out any samples that don’t fall within the desired time interval.

With the sample type and predicate created, it builds the query. This query returns any samples measuring dietary energy consumed that fall within the time frame. There is no limit placed on the number of samples it returns, and the results are not sorted.

The results handler starts by checking to see whether an error occurred. If there is an error, it prints a log message to the console and aborts. Otherwise, it dispatches back to the main thread to update the UI.

The dispatch block begins by clearing the view controller’s array of food items. Next, it iterates over each result, grabbing the name of the food (from the metadata) and the amount of energy (in joules). It uses these values to create a new food item, which it adds to the food item array.

After all the results have been processed, the results handler asks the table view to load the new data.

After the results handler’s block is defined, the query is complete. This query is then executed using the HealthKit store.


Initializing Sample Queries


A value indicating that the query returns all the matching samples in the HealthKit store.

Getting Property Data


The maximum number of samples that this query returns.


The sort descriptors that specify the order of the results returned by this query.

Setting Limits


A value indicating that the query returns all the matching samples in the HealthKit store.


Inherits From

See Also

Common Query Types


A query that accesses the series data associated with a quantity sample.


A query that returns only recent changes to the HealthKit store, including a snapshot of new changes and continuous monitoring as a long-running query.


A long-running query that monitors the HealthKit store and updates your app when the HealthKit store saves or deletes a matching sample.


A query that performs complex searches based on the correlation’s contents, and returns a snapshot of all matching samples.


A query that returns a snapshot of all matching documents currently saved in the HealthKit store.


A query that returns the heartbeat data contained in a heartbeat series sample.


An abstract class for all the query classes in HealthKit.