0
我试图从HealthKit中提取数据,正在以正确的速度提取数据。我认为GCD建立的方式可能有问题。使用GCD加载数据非常慢
下面是代码:
- (void)loadGraphDataForType:(NSString *)type withDuration:(int)graphDuration {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *interval = [NSDateComponents new];
if (graphDuration == 1) {
interval.hour = 1;
} else {
interval.day = 1;
}
NSMutableArray *arrayOfValues = [NSMutableArray new];
NSDate *anchorDate = [calendar startOfDayForDate:[NSDate date]];
HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:type];
dispatch_queue_t queue = dispatch_queue_create([@"graph.queue" UTF8String], DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
dispatch_semaphore_t lock = dispatch_semaphore_create(0);
HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:nil options:HKStatisticsOptionCumulativeSum anchorDate:anchorDate intervalComponents:interval];
query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *results, NSError *error) {
if (error) {
NSLog(@"Error: %@ %@", error, [error userInfo]);
} else {
NSDate *endDate = [NSDate date];
NSDate *startDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:-graphDuration toDate:endDate options:0];
[results enumerateStatisticsFromDate:startDate toDate:endDate withBlock:^(HKStatistics *result, BOOL *stop) {
HKQuantity *quantity = result.sumQuantity;
if (quantity != nil) {
double value = 0;
//Steps Traveled
value = [quantity doubleValueForUnit:[HKUnit countUnit]];
int intValue = (int)value;
[arrayOfValues addObject:@(intValue)];
} else {
[arrayOfValues addObject:@0];
}
}];
dispatch_semaphore_signal(lock);
}
};
[self.healthStore executeQuery:query];
dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
});
dispatch_group_notify(group, queue, ^{
graphData = [PNLineChartData new];
graphData.color = [UIColor whiteColor];
graphData.itemCount = [arrayOfValues count];
graphData.getData = ^(NSUInteger index) {
CGFloat yValue = [arrayOfValues[index] floatValue];
return [PNLineChartDataItem dataItemWithY:yValue];
};
graph.chartData = @[graphData];
[graph strokeChart];
});
}
如果我把一个破发点,其中图获取项目计数,它显示25(这是正确的),我可以看到阵列内的数据,但该图需要5分钟才能显示出来。我现在尝试了几个不同的库,它们都表现相同,所以我认为它是我的代码中的东西造成的。
我不是那么熟悉GCD,所以我确信它是那样的。
如果有人有任何建议,我将不胜感激。
谢谢!
你打败了我,我在回答,我刚刚摆脱了所有的信号量和所有的垃圾。我只是将结果发送到每个Apple文档的主队列,现在一切正常。谢谢! https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKStatisticsCollectionQuery_Class/ –
很高兴我能帮到你。 – jarryd