【发布时间】:2016-04-04 09:00:25
【问题描述】:
我正在使用 HealthKit 从我的 iOS 设备读取步数数据。
这是我的代码:
if ([HKHealthStore isHealthDataAvailable]) {
__block double stepsCount = 0.0;
self.healthStore = [[HKHealthStore alloc] init];
NSSet *stepsType =[NSSet setWithObject:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]];
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:stepsType completion:^(BOOL success, NSError * _Nullable error) {
if (success) {
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:nil limit:HKObjectQueryNoLimit sortDescriptors:nil resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
if (error != nil) {
NSLog(@"results: %lu", (unsigned long)[results count]);
for (HKQuantitySample *result in results) {
stepsCount += [result.quantity doubleValueForUnit:[HKUnit countUnit]];
}
NSLog(@"Steps Count: %f", stepsCount);
} else {
NSLog(@"error:%@", error);
}];
[self.healthStore executeQuery:sampleQuery];
[self.healthStore stopQuery:sampleQuery];
NSLog(@"steps:%f",stepsCount);
}
}];
}
我在具有步数数据的 iPhone6 上构建并运行代码,在设置 -> 隐私 -> 健康中,确实允许该应用读取数据,但日志区域仅显示:
steps:0.000000
我在 for 循环和 NSLog(@"error:%@", error) 上设置了一个断点,但应用程序没有中断。
有人可以帮忙吗?
【问题讨论】:
-
你没有检查错误参数?你通过
results: %lu日志吗?我不确定那是你应该stopQuery:的地方。看起来很奇怪。 -
@Larme 我还检查了
error,但NSLog(@"error:%@", error)没有记录任何内容。
标签: ios objective-c healthkit hksamplequery