How do I download Healthkit step and distance data?

隐身守侯 提交于 2019-12-08 13:23:31

I'm not sure it can help you but this is how I get steps

+ (void)readUsersStepFromHK:(NSDate*)startDate end:(NSDate*)endDate
{
stepBegin=startDate;
stepEnd=endDate;
if ([HKHealthStore isHealthDataAvailable])
{
    HKUnit *unit = [HKUnit countUnit];

    HKQuantityType *stepCountType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];


    [self fetchMostRecentDataOfQuantityType:stepCountType withCompletion:^(HKQuantity *mostRecentQuantity, NSError *error) {
        if (!mostRecentQuantity)
        {
            //Either an error

        }
        else
        {
            double temCout=[mostRecentQuantity doubleValueForUnit:unit];
            coutStep=temCout;

        }
    }];

}
}

+ (void)fetchMostRecentDataOfQuantityType:(HKQuantityType *)quantityType withCompletion:(void (^)(HKQuantity *mostRecentQuantity, NSError *error))completion {
NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];
//=======
NSDate *startDate, *endDate; // Whatever you need in your case
startDate=stepBegin;
endDate=stepEnd;
// Your interval: sum by hour
NSDateComponents *intervalComponents = [[NSDateComponents alloc] init];
intervalComponents.hour = 1;

// Example predicate
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];

// Since we are interested in retrieving the user's latest sample, we sort the samples in descending order, and set the limit to 1. We are not filtering the data, and so the predicate is set to nil.
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType predicate:predicate limit:100 sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
    if (!results) {
        if (completion) {
            completion(nil, error);
        }
        return;
    }
    if (completion) {
        // If quantity isn't in the database, return nil in the completion block.
        HKQuantitySample *quantitySample = results.firstObject;
        HKQuantity *quantity = quantitySample.quantity;

        completion(quantity, error);
    }
}];

[healthStore executeQuery:query];
}

hop this help !

suhaib
if (NSClassFromString(@"HKHealthStore") && [HKHealthStore isHealthDataAvailable])
{
    // Add your HealthKit code here
    HKHealthStore *healthStore = [[HKHealthStore alloc] init];

    // Share body mass, height and body mass index etc....
    NSSet *shareObjectTypes = [NSSet setWithObjects:
                               [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass],
                               [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight],
                               [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
                               [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
                               nil];

    // Read date of birth, biological sex and step count etc
    NSSet *readObjectTypes  = [NSSet setWithObjects:
                               [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth],
                               [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
                               [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
                               [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
                               nil];

    HKQuantityType *type = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

    // Request access
    [healthStore requestAuthorizationToShareTypes:shareObjectTypes
                                        readTypes:readObjectTypes
                                       completion:^(BOOL success, NSError *error) {

                                           if(success == YES)
                                           {
                                               //[healthStore ];
                                               //NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];

                                              // NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES];
                                               NSSortDescriptor *timeSortDescription = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];
                                               HKSampleQuery    *query = [[HKSampleQuery alloc] initWithSampleType:type
                                                                                                         predicate:nil
                                                                                                             limit:HKObjectQueryNoLimit
                                                                                                   sortDescriptors:@[timeSortDescription]
                                                                                                    resultsHandler:^(HKSampleQuery *query, NSArray *result, NSError *error){

                                                                                                        NSLog(@"RESULT  : =>  %@",result);
                                                                                                        if(!error && result)
                                                                                                        { long totalSteps=0;
                                                                                                            for(HKQuantitySample *quantitySample in result)
                                                                                                            {
                                                                                                                // your code here


                                                                                                            HKQuantity  *quantity=quantitySample.quantity;
                                                                                                                 //HKQuantity *quantity = quantitySample.quantity;
                                                                                                                NSString *string=[NSString stringWithFormat:@"%@",quantity];
                                                                                                                NSString *newString1 = [string stringByReplacingOccurrencesOfString:@" count" withString:@""];

                                                                                                                NSInteger count=[newString1 integerValue];
                                                                                                                totalSteps=totalSteps+count;
                                                                                                            }
                                                                                                            //using total steps
                                                                                                        }
                                                                                                    }];
                                               [healthStore executeQuery:query];
                                           }
                                           else
                                           {
                                               // Determine if it was an error or if the
                                               // user just canceld the authorization request
                                               //Fit_AAPLprofileviewcontroller_m.html
                                           }

                                       }];
}

You can perform a simple query for steps (and any other samples stored in HealthKit) using a HKSampleQuery. If you would like HealthKit to aggregate the samples for you, you could use a HKStatisticsQuery or HKStatisticsCollectionQuery instead. Before querying for the user's HealthKit data, you will need to ask for permission to access it with -[HKHealthStore requestAuthorizationToShareTypes:readTypes:completion: ].

For a general introduction to writing applications that integrate with HealthKit, I recommend that you watch the WWDC talk.

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