-(void)requestHKHealthStore{
self.healthStore = [[HKHealthStore alloc] init];
NSLog(@"%d",[HKHealthStore isHealthDataAvailable]);
// 判读是否有权限
if ([HKHealthStore isHealthDataAvailable]){
// 请求权限
HKQuantityType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSet *shareSet = [NSSet setWithObjects:sampleType, nil];
HKQuantityType *read = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSet *readSet = [NSSet setWithObjects:read, nil];
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:readSet completion:^(BOOL success, NSError * _Nullable error) {
if (success) {
NSLog(@" 请求权限成功");
// 获取步数
[self getTodyStepNumberForHealthKit];
} else{
NSLog(@"error %@", error);
}
}];
};
}
- (void)getTodyStepNumberForHealthKit{
// 读取步数
// 设置开始和结束日期为您查询感兴趣的
NSDate *startDate, *endDate;
endDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
startDate = [calendar startOfDayForDate:now];
endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
NSLog(@"startDate %@, endDate %@", startDate, now);
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
// 创建一个谓词集开始/结束日期范围查询
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];
//创建一个类描述符开始日期进行排序
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES];
// __weak UILabel *numberLabel = self.showView.existStpNumberLabel;
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[sortDescriptor] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
if(!error && results)
{
CGFloat sum = 0.0f;
for(HKQuantitySample *sample in results)
{
NSLog(@"==%@", sample);
HKUnit *unit = [HKUnit unitFromString:@"count"];
CGFloat number = [sample.quantity doubleValueForUnit:unit];
sum += number;
//总得步数
NSLog(@"+=+%f",sum);
if ([ToolsManager loginUser].identifier > 0) {
// 获取步数提交步数请求协议--这里直接请求是错误的--还放在循环里了--特错大错--要放在主线程里去请求协议--放在循环外面啊
// [self requestTheyCountSubmit:sum];
}
}
dispatch_async(dispatch_get_main_queue(), ^{
// numberLabel.text = @(sum).description;
});
}
}];
[self.healthStore executeQuery:sampleQuery];
}
网友评论