Here is my code...
Calories.m
-(void)queryForQuantityTypeIdentifier: (HKQuantityTypeIdentifier)quantityTypeIdentifier;
{
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:quantityTypeIdentifier];
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:nil limit:HKObjectQueryNoLimit sortDescriptors:nil resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
if (!results) {
NSLog(@"Error is fetching %@ %@",quantityTypeIdentifier, error);
}
else if(results.count>0)
{
if (quantityTypeIdentifier == HKQuantityTypeIdentifierStepCount)
{
self->_stepsTakenSampleArray = [results mutableCopy];
}
dispatch_async(dispatch_get_main_queue(), ^(){
NSNotification *stepsDataRetrivedNotification = [NSNotification notificationWithName:@"StepsDataRetrivedNotification" object:nil];
[[NSNotificationCenter defaultCenter] postNotification:stepsDataRetrivedNotification];
});
}
[self->store stopQuery:query];
}];
dispatch_async(dispatch_get_main_queue(), ^{
self->appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
self->store = [[self->appDelegate hkOperator] hkStore];
[self->store executeQuery:query];
});
}
HealthKitOperator.m
-(void)enableStore
{
_hkStore= [[HKHealthStore alloc] init];
[self requestPermissions];
HKSampleType *quantityType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
stepsObserverQuery = [[HKObserverQuery alloc] initWithSampleType:quantityType predicate:nil updateHandler:^(HKObserverQuery *query,HKObserverQueryCompletionHandler completionHandler, NSError *error) {
if (completionHandler) {
dispatch_async(dispatch_get_main_queue(), ^()
{
[self->_calories querySteps];
});
}
}];
[_hkStore executeQuery:stepsObserverQuery];
}
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if (_hkOperator.hkAuthorised)
{
[_hkOperator.hkStore enableBackgroundDeliveryForType: [HKQuantityType quantityTypeForIdentifier: HKQuantityTypeIdentifierStepCount] frequency:HKUpdateFrequencyHourly withCompletion:^(BOOL success, NSError *error) {
[self->_hkOperator.calories querySteps];
}];
}
return YES;
}